使用stringstream读取浮点值时出现奇怪的错误
strange failure using stringstream to read a float value
我有以下简单的代码,读取浮点值(双)使用c++ stringstream
。我使用stringstream::good来检测读取是否成功。奇怪的是,该值被读入float变量,但good()
返回false。底部的代码返回:
failed: 3.14159
我在mingw32下使用gcc 4.8.1编译代码,使用g++ -std=c++11 test.cpp
。
知道为什么这个读数不是good
吗?怎样才能正确判断浮点数是否被成功读取呢?
#include <sstream>
#include <iostream>
using namespace std;
void readFloat(string s) {
double i = 0!;
stringstream ss(s);
ss >> i;
if (ss.good())
cout << "read: " << i << endl;
else
cout << "failed: " << i << endl;
}
main() {
readFloat("3.14159");
}
当流在提取过程中到达流的末尾时,他们将流状态中的std::ios_base::eofbit
设置为提醒用户不能再读取字符。这意味着good()
不再返回true,直到流状态被清除。
一般来说,good()
不是确定I/O成功的可靠方法。good()
作为条件意味着没有设置每个位(包括eofbit
),如果您只是想确定I/O操作是否成功,这可能会产生误导。因为设置了eofbit
,所以程序告诉您I/O操作失败了,而实际上没有。
相反,最好将整个提取包装在一个条件中,以确定它是否成功。在流中将隐式强制转换为布尔类型,并且流将在内部调用!this->fail()
,这是比good()
更好的选择:
if (ss >> i) {
std::cout << "read: " << i << std::endl;
}
else {
std::cout << "failed: " << i << std::endl;
}
这里没有奇怪的行为
stringstream::好()
如果到达文件的末尾,函数返回false。如果你在"ss>> i"之前测试良好,我相信它会返回true。
一个好的测试方法是:
double i = 0.0;
std::stringstream ss(s);
if (!ss.good())
throw std::exception("Stream not good");
ss >> i;
if (!ss.eof())
throw std::exception("Stream not read entirely");
相关文章:
- 分段错误 - 读取初始化指针的数组
- 在指向函数中读取变量时出现分割错误
- 读取某些文件时出现分段错误,似乎与文件大小无关
- 从对象C++中的文件读取内容时出现分段错误
- 我编写了以下代码来读取C++矩阵,然后打印其行和列.我收到此错误
- 可能的 ComputeCPP SYCL 错误读取嵌套缓冲区
- Eigen SparseLU解决错误读取访问冲突,这>m_sup_to_col被0x111011101110112
- 访问违规读取位置和错误读取字符串的错误
- libpng 错误:读取错误
- 错误读取字符到矩阵
- 分段错误读取 JSON 文件
- 斯特托克获取分段错误读取文件
- ifstream 初始化错误 - 读取字符时出错
- 读取错误-读取时无限
- 异常错误:读取位置0xDDDDDDDD时发生访问冲突
- 如何修复此错误读取位置0x00000008时发生访问冲突
- GDB:<错误读取变量>,带有 C++ 向量
- 找不到错误 读取大小 4 瓦尔格林德无效
- 分割错误读取文件
- libpng错误:读取错误(Visual Studio 2010)