使用stoi()方法将字符串转换为int,但即使存在alpahabet,也可以将其转换为int。
string str1 = "45";
string str2 = "31337 test";
int myint1 = stoi(str1); // 45
int myint2 = stoi(str2); // 31337
str2转换为int,但是我不希望这种转换,因为它具有字母。是否有任何捕捉或阻止此转换的方法。
您可以检查已处理的字符数。
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()) {
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句