如何允许我的程序成功读取数字包含的文件

How Do I Allow My Program to Successfully Read The Numbers Contained a File?

本文关键字:数字 包含 文件 读取 成功 何允许 我的 程序      更新时间:2023-10-16

我的任务是编写一个程序,该程序读取一个充满称为random的数字的文件的内容.txt该文件将这些数字分解并确定它们的总和,平均值和数字的数量。但是,用户必须手动输入此文件的名称。在测试该程序时,它永远不会识别随机.txt存在,我不知道是什么原因造成的。如果他的程序中存在任何其他逻辑错误,我不知道它们,因为我必须先让程序能够读取随机.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 itn";
    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;
 }

代码在其当前状态下编译,因此尽管程序未按预期运行,但我不会收到任何错误消息。

在你的

while循环中直接尝试这个条件它可能会起作用。

while(input >> number)
{
 i++;
 sum+=number;
}

我用一个带有随机数列表的文件"random.txt"测试了你的代码,它工作正常,所以你的代码没有问题。

这意味着您编译错误,或者您的可执行文件位于与随机文件不同的文件夹中.txt。问题可能是您的随机.txt文件的位置;确保将其放置在生成已编译.exe文件的同一目录中(某些 IDE 可能会将二进制文件输出到项目内的子文件夹中(。