stoi当字符串不符合规范时,会抛出异常,所以你应该捕获异常来做。
#include
#include
#include
using namespace std;
int main()
{
std::string y = "253647586946334221002101219955219971002";
int x;
try {
x = stoi(y);
}
catch (std::invalid_argument&){
// if no conversion could be performed
cout << "invalid_argument" << endl;
}
catch (std::out_of_range&){
// if the converted value would fall out of the range of the result type
// or if the underlying function (std::strtol or std::strtoull) sets errno
// to erange.
cout << "out of range" << endl;
}
catch (...) {
// everything else
cout << "something else" << endl;
}
return 0;
}