如何允许我的程序成功读取数字包含的文件
How Do I Allow My Program to Successfully Read The Numbers Contained a File?
我的任务是编写一个程序,该程序读取一个充满称为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 可能会将二进制文件输出到项目内的子文件夹中(。
相关文章:
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何确定integer_sequence在编译时是否包含给定的数字?
- 如何生成仅包含 0 和 9 的数字
- 如何将较大数字中从0到9的单个数字放入只包含数字的数组中
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 正则表达式,包含名称 + "string" + 数字,没有其他内容
- 如何识别字符串只包含数字
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 如何对包含数字和符号的字符串进行排序?
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何允许我的程序成功读取数字包含的文件
- 如何在包含数字的.bmp(二进制图像)中执行组件标记9 4 3 6
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- C++ 检查字符串是否至少包含 1 位数字和 1 个字母
- 如何为字符串编写正则表达式,其中包含一个数字至少一个数字,并且不包含任何字母
- 如果QString包含一个数字
- 用于计算不包含给定数字的第n个数字的程序
- 分类包含数字和单词的字符串向量
- 打印每行包含 n 个数字的数组