C++ 将字符串转换为int

Viv*_*vek 2 c++ c++11

使用stoi()方法将字符串转换为int,但即使有字母,它也会转换为int。

string str1 = "45";
string str2 = "31337 test"; 

int myint1 = stoi(str1); // 45
int myint2 = stoi(str2); // 31337
Run Code Online (Sandbox Code Playgroud)

str2 被转换为 int,但我不想要这种转换,因为它有字母表。是否有任何方法可以捕获或阻止这种转换。

son*_*yao 6

您可以检查已处理的字符数。

string str2 = "31337 test"; 
std::size_t num;

int myint2 = stoi(str2, &num); // 31337
//                      ^^^^

// num (the number of characters processed) would be 5
if (num != str2.length()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)