我的任务是编写一个程序,该程序读取一个充满数字的文件,该文件名为random.txt,它将分配这些数字并确定其总和,均值和数字数。但是,用户必须手动输入该文件的名称。测试该程序时,它永远不会识别出random.txt存在,并且我不知道是什么原因造成的。如果他的程序中存在其他逻辑错误,我将不知道这些错误,因为在查看结果之前,我必须首先使该程序能够读取random.txt。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int i=0,num, sum=0;
double average;
ifstream input;
input.open("random.txt"); //open file
if(input.fail()) //is it ok?
{ cout<<"file did not open please check it\n";
system("pause");
return 1;
}
input>>num;
while(input)
{i++;
sum+=num;
input>>num;
}
average=sum/(double)i;
cout<<"The number of numbers in the file is: "<<i<<endl;
cout<<"The sum of all the numbers in the file is: "<<sum<<endl;
cout<<"The average of all the numbers in the file: "<<average<<endl;
input.close();
system("pause");
return 0;
}
代码在当前状态下编译,因此尽管程序未按预期运行,但我没有收到任何错误消息。
答案 0 :(得分:0)
在您的while循环中直接尝试这种情况 它可能会工作。
while(input >> number)
{
i++;
sum+=number;
}
答案 1 :(得分:0)
我使用带有随机数列表的文件“ random.txt”测试了您的代码,它可以正常工作,因此您的代码没有错。
这意味着您编译错误,或者您的可执行文件位于与random.txt文件不同的文件夹中。问题可能出在您random.txt文件的位置。确保将其放在生成编译后的.exe文件的同一目录中(某些IDE可能会将二进制文件输出到项目内部的子文件夹中)。