安全地将std :: string_view转换为int(如stoi或atoi) [英] Safely convert std::string_view to int (like stoi or atoi)
问题描述
是否存在将 std :: string_view
转换为 int
的安全标准方法?
Is there a safe standard way to convert std::string_view
to int
?
由于C ++ 11 std :: string
我们使用 stoi
转换为 int
:
Since C++11 std::string
lets us use stoi
to convert to 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
,但是必须非常小心,例如:
But stoi
does not support std::string_view
. So alternatively, we could use atoi
, but one has to be very careful, e.g.:
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
不能简单地插入/添加一个。)
So atoi
does not work either, since it is based off the null-terminator '\0'
(and e.g. sv.substr
cannot simply insert/add one).
现在,由于C ++ 17中还有 from_chars
,但在提供不良输入时似乎不会抛出该错误:
Now, since C++17 there is also from_chars
, but it does not seem to throw when providing poor inputs:
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 函数不会抛出该异常,它只会返回一个类型的值 from_chars_result
基本上是具有两个字段的结构:
The std::from_chars function does not throw, it only returns a value of type from_chars_result
which is basically a struct with two fields:
struct from_chars_result {
const char* ptr;
std::errc ec;
};
您应检查 ptr
的值,然后 ec
当函数返回时:
You should inspect the values of ptr
and ec
when the function returns:
#include <iostream>
#include <string>
#include <charconv>
int main()
{
int i3;
std::string_view sv = "abc";
auto result = std::from_chars(sv.data(), sv.data() + sv.size(), i3);
if (result.ec == std::errc::invalid_argument) {
std::cout << "Could not convert.";
}
}
这篇关于安全地将std :: string_view转换为int(如stoi或atoi)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!