qiu*_*bit 2 c++ fstream ifstream
首先要做的事情 - 我有一个文本文件,其中有二进制数,每行一个数字.我正在尝试阅读它们并在C++程序中总结它们.我写了一个函数,将它们转换为十进制并在此之后添加它们,我确信该函数没问题.这是我的问题 - 对于这两种不同的阅读文本文件的方式,我得到了不同的结果(这些结果中只有一个是正确的)[我的函数是十进制()]:
ifstream file;
file.open("sample.txt");
int sum = 0;
string BinaryNumber;
while (!file.eof()){
file >> BinaryNumber;
sum+=decimal(BinaryNumber);
}
Run Code Online (Sandbox Code Playgroud)
这样我的总和太大了,但数量很少.
ifstream file;
file.open("sample.txt");
int sum = 0;
string BinaryNumber;
while (file >> BinaryNumber){
sum+=decimal(BinaryNumber);
}
Run Code Online (Sandbox Code Playgroud)
这种方式给了我正确的金额.经过一些测试后,我得出结论,eof()的while循环比另一个循环更多迭代.所以我的问题是 - 从文本文件中读取这两种方式有什么区别?为什么第一个while循环给了我错误的结果,这可能是它正在进行的额外迭代?
区别在于>>首先读取数据,然后告诉您它是否成功,同时file.eof()在读取之前进行检查.这就是为什么你用这种file.eof()方法得到一个额外的读取,并且该读取是无效的.
您可以file.eof()通过将检查移动到读取后的位置来修改代码以使其工作,如下所示:
// This code has a problem, too!
while (true) { // We do not know if it's EOF until we try to read
file >> BinaryNumber; // Try reading first
if (file.eof()) { // Now it's OK to check for EOF
break; // We're at the end of file - exit the loop
}
sum+=decimal(BinaryNumber);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果最后一个数据条目后面没有分隔符,则此代码将中断.所以你的第二种方法(即检查结果>>)是正确的.
编辑:这篇文章是为了回应这个评论而编辑的.