std::string str = "12345";
int i1 = stoi(str); // Works, have i1 = 12345
int i2 = stoi(str.substr(1,2)); // Works, have i2 = 23
try {
int i3 = stoi(std::string("abc"));
catch(const std::exception& e) {
std::cout << e.what() << std::endl; // Correctly throws 'invalid stoi argument'
但是 stoi
不支持 std::string_view
。因此,或者,我们可以使用 atoi
,但必须非常小心,例如:
std::string_view sv = "12345";
int i1 = atoi(sv.data()); // Works, have i1 = 12345
int i2 = atoi(sv.substr(1,2).data()); // Works, but wrong, have i2 = 2345, not 23
所以 atoi
也不起作用,因为它基于空终止符 '\0'
(例如 sv.substr
不能简单地插入/添加一个)。
现在,由于 C++17 还有 from_chars
,但是在提供不良输入时似乎不会抛出:
try {
int i3;
std::string_view sv = "abc";
std::from_chars(sv.data(), sv.data() + sv.size(), i3);
catch (const std::exception& e) {
std::cout << e.what() << std::endl; // Does not get called
原文由 Phil-ZXX 发布,翻译遵循 CC BY-SA 4.0 许可协议