✔ 最佳答案
This program accepts a file name from the command line (argv[1]), opens the file and read its contents. All numbers are then added and counted. When no more data is found, the average is calculated, but without checking to see if any valid input has been entered.
Here are my comments, added at the end of each line:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char**argv)
{
if(argc<=1) // print usage if filename not supplied
{
printf("Usage: average filename\n");
exit(0);
}
ifstream src(argv[1]);
int x;
long sum=0, count=0; // int could overflow, use long
while(src>>x)
{
sum+=x;
++count;
}
if(count>0)cout<<"average:"<<sum/count<<endl; // count could be zero
else printf("No input numbers found\n"); // message if no data found
cin>>x; // prevents execution screen from disappearing
return 0; // return required for integer function
}