Guest User

Untitled

a guest
Feb 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3.  
  4. int main()
  5. {
  6.  
  7.     using namespace std;
  8.     // This will take the file into the program
  9.     ifstream in_stream;
  10.  
  11.     cout << "I am going to take the numbers from the input file and average them." << endl;
  12.  
  13.     // Opens the input file.
  14.     in_stream.open ( "input.dat" );
  15.  
  16.     // If the file fails to open it will close the program and output the statement.
  17.     if ( in_stream.fail( ) )
  18.     {
  19.         cout << "Please check if the file is saved properly. It could not open." << endl;
  20.     }
  21.  
  22.     // Declares the variables to get the average
  23.     double temp, sum = 0;
  24.     int i = 0;
  25.     double average;
  26.  
  27.     // Loops the file until no more numbers can be read
  28.     while (in_stream >> temp)
  29.     {
  30.     sum += temp;
  31.     ++i;
  32.     }
  33.  
  34.     // Final average
  35.     average= sum / i;
  36.  
  37.     // Outputs the average to the screen
  38.     cout << "The average of the numbers is ";
  39.     cout << average;
  40.     cout << endl;
  41.  
  42.     // Closes the file
  43.     in_stream.close ();
  44.  
  45.     cout << "The program will now close." << endl;
  46.  
  47. }
Add Comment
Please, Sign In to add comment