为什么std::stol不适用于科学记数法
Why does std::stol not work with scientific notation?
我有这个代码:
#include <iostream>
int main() {
long l1 = std::stol("4.2e+7");
long l2 = std::stol("3E+7");
long l3 = 3E7;
printf("%dn%dn%dn", l1, l2, l3);
return 0;
}
预期输出42000000, 3000000, 3000000
但实际输出为(在 ideone C++14 和 VS2013 上测试(:
4
3
30000000
为什么会这样,无论如何都要让std::stol
考虑到科学记数法?
您要查找的函数是std::stof
而不是std::stol
。 std::stof
在引擎盖下调用std::strtod
,它支持科学计数法。但是,std::stol
在引擎盖下称std::strtol
,但事实并非如此。
#include <iostream>
#include <string>
int main() {
long l1 = std::stof("4.2e+7");
long l2 = std::stof("3E+7");
long l3 = 3E7;
std::cout << l1 << "n" << l2 << "n" << l3;
return 0;
}
输出:
42000000
30000000
30000000
仅供参考,对于其他偶然发现此解决方案的人来说,在包含指数的科学记数法数字的字符串中读取的更强大的方法是使用 std::stringstream
,如 C++ 食谱和此 StackOverflow 问题("使用 stringstream 浮点的字符串"(中所述
实际上,像这样:
#include <sstream>
#include <string>
std::string number = "1.0E+6";
std::stringstream ss(str);
double d = 0;
ss >> d; // d = 1.0E6
相关文章:
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 结构化绑定是否适用于 std::vector?
- 没有适用于 std::unique_ptr 的适当默认构造函数
- 适用于 std::unique_ptr 的内存高效自定义删除器?
- std::string 是否仅适用于 c++ 中的'std::cin'
- 为什么不区分大小写适用于 std::unordered_set的 std::hash 函数?
- 为什么我的"choose k from n"算法适用于 std::vector,而不适用于 std::map?
- 无法获得 boost::spirit parser&lexer 适用于 std::string 或 int 或 double 以外的令牌类型
- 重载分辨率如何适用于 std::vector:<int>:insert
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 在C++std::streams中,失败后,如何获得失败原因?必需:线程安全,适用于Windows和Linux(或至少M
- 适用于 MacOS 的"-std=gnu++0x"选项
- 警告:扩展初始值设定项列表仅适用于-std=c++0x或-std=gnu++0x
- 警告:扩展初始化器列表仅适用于STD c++ 11
- 自定义迭代器适用于std::sort,但不适用于tbb::parallel_sort
- 不在异常中嵌入std::字符串的规则是否仍然适用于move构造函数
- boost::variant是否适用于std::string
- 如何包装对"std::thread"构造函数的调用?(适用于gcc、VS和icpc)
- 可变参数模板转换为 std::function<R(ARGS...)>适用于 GCC 而不是 MSVC2013,为什么?