是否有一种安全的标准方法可以转换std::string_view为int?
由于 C++11std::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'
}
Run Code Online (Sandbox Code Playgroud)
但stoi不支持std::string_view。因此,或者,我们可以使用atoi,但必须非常小心,例如:
std::string_view sv = "12345";
int i1 = atoi(sv.data()); // Works, have …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 C++20 编译器转换std::string_view为浮点数,而无需中间转换(这将导致额外的堆分配)。std::string
#include <iostream>
#include <charconv>
int main() {
std::string_view s = "123.4";
float x;
std::from_chars(s.data(), s.data() + s.size(), x);
std::cout << x << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但我无法编译这段代码:
error: no matching function for call to 'from_chars(std::basic_string_view<char>::const_pointer, std::basic_string_view<char>::const_pointer, float&)'
Run Code Online (Sandbox Code Playgroud)
我做错了什么?