//****************************************************** v. 1/20/05 // Purpose: Count the values in a file. // This can serve as an initial check for validity of // data file formats. // Usage: count [] < // File reads standard input, so you can use redirection // or piping. // To use, you can indicate how many values should be in // the file as an arguement. The program then reports // mismatches. If you don't indicate the number of expected // values in the input file, the number read are reported. // It also reports the sum of all numbers in the file. (just // to compare different files). // It has a "debug" mode. Read code below. // Name: M. Overstreet //******************************************************************** // Listing contents: // Purpose // Usage // Pre & Postconditions // Reuse instructions // Compilation instructions // Source code //******************************************************************** // Precondtion: // file is assumed to contain only numeric values. // Postcondition: // If the size of the file matches, this is reported as a match" // If the size does not match, the actual number read is reported. // In both cases, the sum of values is also displayed. //******************************************************************** // Reuse instructions: this is so short, it has limited reuse // potential, but the code may server as an example of // command line parameter passing and error handling. //******************************************************************** // Compilation // Under UNIX or Linux: // g++ -o count -g count.cpp //******************************************************************** using namespace std; #include // for cout #include // for atoi which converts char arrays to ints int main( int argc, char *argv[] ) { double inVar, inTot; int inCt = 0, debug = 0, numExpected; // Check for command line parameters if ( argc>1 ) numExpected = atoi( argv[1] ); else numExpected = 10000; // If three parameters, assume debug mode if (argc==3) { cout << "debug mode. print all values read" << endl; debug = 1; } cin >> inVar; while( cin ) { inCt++; inTot += inVar; if ( debug ) cout << inVar << endl; cin >> inVar; } if ( inCt == numExpected ) cout << "File has right number of values, " << numExpected << " values found." << endl; else cout << "File seems to have the wrong number of values." << endl << inCt << " values read" << endl << numExpected << " expected" << endl; cout << inTot << " total of values read." << endl; return 0; }