我无法从文本文件中读取数据。数据采用以下格式:
Balto 85 83 77 91 76
Mickey 80 90 95 93 48
Minnie 78 81 11 90 73
Doc 92 83 30 69 87
Pluto 85 72 49 75 63
Grumpy 27 31 52 74 83
我必须计算每个名字前面的整数之和。没有字符串,没有数组!有人能帮帮我吗?
到目前为止我尝试过的代码是:int main()
{
ifstream infile;
char b;
int x, i=0, sum=0, j=1;
infile.open("input.txt");
if (infile.fail())
{
cout<<"Unable To Open Input File, File Not Found!!"<<endl;
exit(1);
}
while (i < 6)
{
infile.get(b);
while (b != ' ')
{
cout<<b;
infile.get(b);
}
infile>> x;
while (j<=5)
{
sum = sum + x;
infile>> x;
j++;
}
cout<<"'s Average is: "<<sum/5<<endl;
i++;
}
答案 0 :(得分:0)
问题在于:
while (j<=5) {
sum = sum + x;
infile>> x;
j++;
}
第一行j
始终为5.因此,获取数字并计算平均值的循环根本不会启动。只需在循环后将j
重置为1:
while (j<=5) {
sum += x;
infile >> x;
j++;
}
cout << "Average is: "<< sum / 5.0f << endl;
i++;
j = 1;
sum = 0;