に変換する安全な標準的な方法はありますか?std::string_view
int
C++11では次のように変換std::string
できます:stoi
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
nullターミネータに基づいているため'\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
}