首选创建一个包含数字的文本文件。该文件命名1.txt
c++程序实现如下:
#include<iostream> #include<fstream>//文件I/O支持 #include<cstdlib>//提供exit() const int SIZE = 60;//限制变量 int main() { using namespace std; char filename[SIZE]; ifstream inFile;//对象输入 cout << "enter name of data file"; cin.getline(filename, SIZE); inFile.open(filename);//关联文件 if (!inFile.good())//是否打开文件 { cout << "could not open the file" << filename << endl; cout << "program terminating. "; exit(EXIT_FAILURE); } double value; double sum = 0.0; int count = 0;//读入的数 inFile >> value;//取第一个值 while (inFile.good()) { ++count; sum += value; inFile >> value; } if (inFile.eof()) cout << "end of flie reached. "; else if (inFile.fail()) cout << "input . "; else cout << "input . "; if (count == 0) cout << "no data processed. "; else { cout << "item ream:" << count << endl; cout << "sum: " << sum << endl; cout << "average" << sum / count << endl; } inFile.close(); system("pause"); return 0; }
运行结果: