使用g++
编译器,下面的代码在Macbook上抛出Illegal floating-point format
错误,但是它在g++
和clang++
编译的Fedora上运行时没有错误。
问:为什么它不能在Mac上工作,有什么方法可以让它在Mac上工作吗?
#include <iostream>
#include <sstream>
double stringToReal(std::string str) {
std::istringstream stream(str);
double value;
stream >> value >> std::ws;
if (stream.fail() || !stream.eof()) {
std::cerr << "stringToReal: Illegal floating-point format (" << str << ")";
}
return value;
}
int main() {
std::cout << stringToReal("1.457460091727E12");
return 0;
}
发布于 2016-03-08 18:58:34
在我看来,这就像一个OS错误。尝试在EOF上读取std::ws
是在设置流上的失败位,但它不应该。如果在字符串中添加任何空格,错误就会消失。
更新
实际上,可能是Fedora虫。根据cppreference.com的说法,std::ws
“表现为一个UnformattedInputFunction
”,它说的是关于UnformattedInputFunction
的
如果在输入流上设置了
eofbit
或badbit
,也可以设置failbit
,如果在输入流的异常掩码中启用了failbit
上的异常,则抛出ios_base::failure
。
读取value
设置eof位,因此读取到std::ws
实际上应该设置失败位。
https://stackoverflow.com/questions/35875519
复制相似问题