对于我的班级,我们必须创建一个计算课程数字等级的程序。成绩位于将成为输入文件的文件中。输入文件遵循以下格式:每行包含学生姓氏,一个空格,然后是学生姓氏,然后是一个空格,然后是一行中的10个测验分数,每个分数是由一个空格分隔的整数。程序应该从输入文件读取数据并将其放在具有相同格式的输出文件中,除非在每行的末尾有一个额外的数字(类型为double)。这个数字将是十个奖项的平均数。
此时,我能够让我的程序在输出文件中写入来自输入的数据,但是由于我的计算机速度变慢而且文件大小很大,它会陷入无限循环。它也没有把平均值放在最后一行。 有人有什么建议吗?这章带有I / O流对我来说非常困惑。
我有两组得分,第一组只创建一条线,其余只是无穷大的随机字母,但它不在循环中。
第二个进入无限循环,但如果你关闭它,原始数据将存储在输出文件中,但没有平均值,文件大小也很大。格式化也因某些原因而关闭。 http://prntscr.com/8yl0u6
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
char Name;
int Num_Space, scores;
double total_scores;
outfile.open("Output.dat");
if (outfile.fail())
exit(1);
infile.open("scores.txt");
if (infile.fail())
exit(2);
while (!infile.eof())
{
cout << "in first while loop";
infile.get(Name);
outfile.put(Name);
Num_Space = 0;
while (Num_Space < 2)
{
if (Name == ' ')
{
Num_Space++;
outfile << Name;
}
infile.get(Name);
outfile.put(Name);
}
}
while (infile.eof())
{
total_scores = 0;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
infile >> scores;
total_scores += scores;
outfile << scores;
outfile << total_scores / 10;
}
outfile.close();
infile.close();
return 0;
}
答案 0 :(得分:0)
在这两个循环中,您多次调用get
而未检查eof
,因此您可能会错过您到达文件末尾的事实。
正如评论中所述,eof
并不是你想要检查的。我不知道你的作业的确切范围,但你可能想看看getline这会让你的生活变得轻松。
然后,你的第二个循环是在达到eof之后。如果达到eof,你怎么能指望它仍然可以阅读?在第一个循环中,您需要等待2个空格才能开始阅读下一个名称,而不会在两者之间读取成绩。你需要的是阅读名称,然后阅读所有成绩,然后回到名字上。
此外,您的第二个while
循环非常可怕:您为每列复制完全相同的代码。如果要在文件中添加列,该怎么办?您需要修改您的代码(而不仅仅是其中的数字,您实际上需要复制/粘贴一些代码)!由于它是一项任务,我不会给你固定的代码,但它很容易分解:-)注意:你应该在没有硬编码10
的情况下做到这一点时间。如果要添加列,则更糟糕的是必须只更新一个常量。
顺便说一句,除非我错了,你要总结9个等级并除以10.我建议使用分解版本可以防止出现这样的错误: - )