显然std::stoi
不接受以指数表示法表示整数的字符串,例如"1e3"
(= 1000)。有没有一种简单的方法可以将这样的字符串解析为整数?有人会认为,由于这种符号在 C++ 源代码中有效,因此标准库有一种解析它的方法。
问问题
3625 次
4 回答
4
您可以使用stod
(请参阅文档)通过首先将其解析为双精度来执行此操作。 但是,在回退时要小心精度问题......
#include <iostream> // std::cout
#include <string> // std::string, std::stod
int main () {
std::string text ("1e3");
std::string::size_type sz; // alias of size_t
double result = std::stod(text,&sz);
std::cout << "The result is " << (int)result << std::endl; // outputs 1000
return 0;
}
于 2013-07-02T09:48:31.580 回答
2
有人会认为,由于这种符号在 C++ 源代码中有效,因此标准库有一种解析它的方法。
库和编译器无关。此语法在 C++ 中有效的原因是该语言允许您将类型表达式分配double
给整数变量:
int n = 1E3;
将double
表达式(即类型的数字文字double
)分配给整数变量。
知道这里发生了什么,您应该能够轻松识别标准 C++ 库中满足您需要的函数。
于 2013-07-02T09:51:24.997 回答
0
发出指数符号std::stoi
会经常溢出,而 C++ 中的整数溢出是未定义的行为。
您需要构建自己的,您可以根据您的特定要求定制边缘案例。
我倾向于不沿着这std::stod
条路线走,因为如果double
的int
不可分割的部分double
不能由int
.
于 2013-07-02T09:47:44.447 回答
0
例如,您可以使用标准流将其读取为双精度
double d;
std::cin >> d; //will read scientific notation properly
and then cast it to an int, but obviously double can represent far more values than int, so be careful about that.
于 2013-07-02T09:53:45.187 回答