Files

Another way to read from file

The program also below reads the same file with a name and year born.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Read in name and year born from a file
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
   double num, total=0;
   string name;
   int yearborn, age,count=0;
   ifstream people("c:/mycpp/names.txt"); //input file stream
   if(people) { //file was opened
      cout<<"NAME\tAGE\n";  //heading
      people>>name; //read first before loop!
      while (!people.eof())  { //eof=end of file
         people>>yearborn;
         age=2016-yearborn;
         cout<<name<<"\t"<<age<<"\n"; //print each number
         people>>name; //read next name
         count++;
       }//each person
      people.close(); 
      cout<<count<<" people read\n";
   } //file opened successfully
   else {
      cout<<"File error\n"; //cout is used to notify user of error 
   } //while not end of file 
   system("pause");
   return 0;
} //main 
CODE

The input file has a name and the year born for each person. There can be any white space, but most likely it would have one person on each line.

Jay 1994
Debbie 1976
John 1988
Greg 1954
Carol 1999
Sam 2000 
CODE

output
Please note the following:

The name is read before the loop. If we read a name, we enter the loop and read the year born. The last statement in the loop reads the next name.

NEXT: Read a list of people using getline