stoi是 C++ 中用于将字符串转换为整数的函数。以下是详细的使用方法:

基本语法

#include <string>
using namespace std;

int stoi(const string& str, size_t* pos = 0, int base = 10);

1. 基本用法

#include <iostream>
#include <string>
using namespace std;

int main()
{
// 最简单的用法
string numStr = "123";
int num = stoi(numStr);
cout << num << endl; // 输出: 123

// 带负号的数字
string negative = "-456";
int negNum = stoi(negative);
cout << negNum << endl; // 输出: -456

return 0;
}

2. 获取转换位置

string mixed = "123abc789";
size_t position; // 存储第一个无法转换的字符位置

int result = stoi(mixed, &position);
cout << "转换结果: " << result << endl; // 输出: 123
cout << "停止位置: " << position << endl; // 输出: 3
cout << "剩余字符串: " << mixed.substr(position) << endl; // 输出: abc789

3. 不同进制转换

// 二进制转十进制
string binary = "1010";
int decimal1 = stoi(binary, nullptr, 2);
cout << "二进制 " << binary << " = " << decimal1 << endl; // 输出: 10

// 十六进制转十进制
string hex = "1A";
int decimal2 = stoi(hex, nullptr, 16);
cout << "十六进制 " << hex << " = " << decimal2 << endl; // 输出: 26

// 八进制转十进制
string octal = "12";
int decimal3 = stoi(octal, nullptr, 8);
cout << "八进制 " << octal << " = " << decimal3 << endl; // 输出: 10

4. 错误处理

#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

int main()
{
try
{
// 无效数字字符串
string invalid = "abc123";
int num = stoi(invalid);
cout << num << endl;
}
catch (const invalid_argument& e)
{
cout << "错误: 无效参数 - " << e.what() << endl;
}
catch (const out_of_range& e)
{
cout << "错误: 超出范围 - " << e.what() << endl;
}

return 0;
}

5. 实际应用示例

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
vector<string> numberStrings = {"42", "-99", "3.14", "1000", "abc"};

for (const auto& str : numberStrings)
{
try
{
int num = stoi(str);
cout << "字符串 '" << str << "' 转换为: " << num << endl;
}
catch (const exception& e)
{
cout << "无法转换 '" << str << "': " << e.what() << endl;
}
}

return 0;
}

输出结果:

字符串 '42' 转换为: 42
字符串 '-99' 转换为: -99
字符串 '3.14' 转换为: 3
字符串 '1000' 转换为: 1000
无法转换 'abc': invalid stoi argument

6. 与 char 数组一起使用

// 可以直接使用 char 数组
char charArray[] = "789";
int num1 = stoi(charArray);
cout << num1 << endl; // 输出: 789

// 也可以使用 char 指针
const char* charPtr = "123";
int num2 = stoi(charPtr);
cout << num2 << endl; // 输出: 123

7. 相关函数族

string largeNum = "123456789012345";
long l = stol(largeNum); // 转换为 long
long long ll = stoll(largeNum); // 转换为 long long

unsigned long ul = stoul("4294967295"); // 转换为 unsigned long

float f = stof("3.14"); // 转换为 float
double d = stod("2.71828"); // 转换为 double

注意事项

  • 自动截断:遇到第一个非数字字符(除了开头的正负号)会停止转换
  • 空白字符:开头的空白字符会被忽略
  • 异常安全:建议使用 try-catch 处理可能的异常
  • 性能:对于单个数字字符,使用 c - '0'更高效
  • C++11stoi是 C++11 引入的函数

推荐用法

// 安全转换函数
int safeStoi(const string& str, int defaultValue = 0)
{
try
{
return stoi(str);
}
catch (...)
{
return defaultValue;
}
}

// 使用示例
string input = "123";
int result = safeStoi(input); // 返回 123

string invalid = "abc";
int defaultVal = safeStoi(invalid, -1); // 返回 -1

stoi是一个非常实用的函数,特别适合处理用户输入、文件读取等场景中的字符串到整数的转换。