C++ C++;无限EOF while循环,搜索存档并没有';我找不到类似的
这是我CS编程课上的一个实验室。这是我写的:C++ C++;无限EOF while循环,搜索存档并没有';我找不到类似的,c++,loops,while-loop,eof,C++,Loops,While Loop,Eof,这是我CS编程课上的一个实验室。这是我写的: #include <iostream> #include <fstream> using namespace std; int main() { int grade, avg, count = 0, total = 0; ifstream gradeFile; gradeFile.open("Lab9C.txt"); gradeFile >> grade;
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int grade, avg, count = 0, total = 0;
ifstream gradeFile;
gradeFile.open("Lab9C.txt");
gradeFile >> grade;
while (!gradeFile.eof())
{
cout << "Grades: ";
while (grade != 0)
{
cout << grade << " ";
count++;
total = total + grade;
avg = total / count;
gradeFile >> grade;
}
cout << "Average: " << avg << endl;
}
gradeFile.close();
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
内部等级,平均值,计数=0,总计=0;
ifstream文件;
gradeFile.open(“Lab9C.txt”);
成绩档案>>成绩;
而(!gradeFile.eof())
{
coutEOF未在循环中检查:
while (grade != 0)
{
cout << grade << " ";
count++;
total = total + grade;
avg = total / count;
gradeFile >> grade;
}
顺便说一句,count
和total
不应该在每个内部循环之前初始化吗?@Barmar思考如何修复…@commandersepard类似的附加信息应该在您的问题中,而不是在注释中。@Barmar-我没有包括while(!feof(文件)),因为我在(文件)中没有任何内容。如果您告诉我(!feof())是错误的,那么为什么我在课堂上被教使用这个,eof循环的替代方案是什么?@MikeCAT明白了,我删除了评论并编辑了我的原始问题。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int grade, avg, count = 0, total = 0;
ifstream gradeFile;
gradeFile.open("Lab9C.txt");
for(;;)
{
cout << "Grades: ";
bool inputTaken = false;
while (gradeFile >> grade) // check for EOF in the inner loop
{
inputTaken = true;
if (grade == 0) break;
cout << grade << " ";
count++;
total = total + grade;
avg = total / count;
}
if (!inputTaken) break; // exit from outer loop when no input is taken in inner loop
cout << "Average: " << avg << endl;
}
gradeFile.close();
return 0;
}