lig*_*tom -1 c++ file while-loop
我必须从只有少数数字的文件中读取.阅读它,总结它们就是这样.(学习C++).如果我使用fstream :: eof()函数,它会读取最后一个数字两次,所以我这样做:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file;
int a = 0, sum = 0;
file.open("nums.txt",fstream::in);
if (!file.is_open()) {
cout << "Unable to open file!\n" << endl;
}
while (file >> a) {
cout << a << endl;
sum += a;
}
cout << "Sum: " << sum << endl;
file.close();
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在它不会读取最后一个数字两次,但我不明白while()括号中发生了什么,我想如果我读0就会停止,但它也会读取它.文件>> a实际返回的内容类似于"托管阅读"= 1和"失败"= 0 ??
谢谢
文件>> a实际上是返回的东西
是.它返回对file自身的引用.并且std::fstream可以bool通过它进行上下文转换operator bool
它本质上返回stream fail()成员的逻辑逆.