C++读文件

/*-------------------------------------------------*/
/*  This program generates a summary report from
   a data file that does not have a header record
   or a trailer record.
   The data file has two column data, one is time and
   the other is motion.It's data from a balloon which
   is set in the air for science experiments.In this
   program we count the number of the data and get the
   maximum, minimum and average value of all the data.
   copy from Engineering Problem Solving with C++.
   by Edison Wang   date:     2009-7-22
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
//Declare and initialize objects.
int num_data_pts(0);
double time,motion,sum(0),max,min;
string filename;
ifstream sensor;

//Prompt user for name of input file.
cout << "Enter the name of the input file:";
cin >> filename;
/*
    while (!cin.eof()) {//ctrl+z will terminal
            //Test error state of cin
            if (!cin) {
                cerr << "Error encountered while reading from standard input"
                     << endl;
                //Clear the error state to enable input
                cin.clear();

                //Remove all characters to the end of the line.
                char bad_ch;
                cin.get(bad_ch);
                while (bad_ch!='\n') {
                    cin.get(bad_ch);
                }
                //Prompt the user to reenter input data
                cout << "Enter the name of the input file correctly:";
                cin >> filename;
            }

        }//end while*/


//Open file and read the first data point.
sensor.open(filename.c_str());

if (sensor.fail()) {
cout << "Error opening input file\n";
}
else{
//while not at the end of the file,
//read and accumulate information
sensor >> time >> motion;  //initial input
max = min = motion;
while (!sensor.eof()) {
num_data_pts++;
sum+=motion;
if (motion>max) {
max = motion;
}
if (motion<min) {
min = motion;
}
sensor >> time >>motion;  //input next
}
//Set format flags.
sensor.setf(ios::fixed);
sensor.setf(ios::showpoint);
sensor.precision(2);
//Print summary information
cout <<"Number of sensor readings: "
<<num_data_pts << endl
<<"Average reading:           "
<<sum/num_data_pts<<endl
<<"Maximum reading:           "
<<max <<endl
<<"Minimum reading:           "
<<min <<endl;

//Close file and exit program.
sensor.close();
}//end else
return 0;
}//end main
/*---------------------------------------------------*/

data:
0.0 132.5
0.1 147.2
0.2 148.3
0.3 157.3
0.4 163.2
0.5 158.2
0.6 169.3
0.7 148.2
0.8 137.6
0.9 135.9

本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

posted @ 2009-08-14 08:28  莫忆往西  阅读(129)  评论(0编辑  收藏  举报