是否有一种安全标准的方法将std::string_view
转换为int
?
自从C++11出现后,我们可以使用stoi
将std::string
转换为int
:
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
}
std::from_chars
不会抛出任何异常。相反,它会返回一个错误码。 - Yksisarvinen