Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- int main()
- {
- using namespace std;
- // This will take the file into the program
- ifstream in_stream;
- cout << "I am going to take the numbers from the input file and average them." << endl;
- // Opens the input file.
- in_stream.open ( "input.dat" );
- // If the file fails to open it will close the program and output the statement.
- if ( in_stream.fail( ) )
- {
- cout << "Please check if the file is saved properly. It could not open." << endl;
- }
- // Declares the variables to get the average
- double temp, sum = 0;
- int i = 0;
- double average;
- // Loops the file until no more numbers can be read
- while (in_stream >> temp)
- {
- sum += temp;
- ++i;
- }
- // Final average
- average= sum / i;
- // Outputs the average to the screen
- cout << "The average of the numbers is ";
- cout << average;
- cout << endl;
- // Closes the file
- in_stream.close ();
- cout << "The program will now close." << endl;
- }
Add Comment
Please, Sign In to add comment