Files

The program below reads a list of numbers from a file and prints the total when all of the values have been read in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Read in numbers from a file, print total
#include<iostream>
#include<fstream>
using namespace std;
int main(void) {
 double num, total=0;
 ifstream numbers; //input file stream
 numbers.open("c:/mycpp/numbers.txt"); //associates numbers with file 
 if (numbers.fail()) //maybe the file doesn't exist, or protected 
    cout<<"File error\n"; //cout is used to notify user of error 
 else {
   while (!numbers.eof()) { //eof=end of file
     numbers>>num; //reads a number from the file
     cout<<num<<"\n"; //print each number
     total+=num;
   } //while not end of file
   numbers.close(); 
   cout<<"Total="<<total<<"\n";
 } //file opened successfully
  system("pause");
  return 0;
} //main 
CODE

The input file can have any white space (new line, tab, blanks, etc.) It can also have 0.

2.8 7
3 0
40 0.2
12
CODE

output
Please note the following:

  • Line 7: the variable numbers is an instance of the input file stream class.
  • Line 8: The open statement associates the C++ name, numbers, with the system, or external name of the file.

NEXT: Read a list of people