Files

Reading mixed data from a file

The program below reads a name and year born from a text file.

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
//Read in name and year born from a file
#include<iostream>
#include<fstream>
using namespace std;
int main(void) {
 double num, total=0;
 char name[15];
 int yearborn, age,count=0;
 ifstream people; //input file stream
 people.open("c:/mycpp/names.txt"); //associates numbers with file 
 if (people.fail()) //maybe the file doesn't exist, or protected 
    cout<<"File error\n"; //cout is used to notify user of error 
 else {
   cout<<"NAME\tAGE\n";  //heading
   people>>name; //read first before loop!
   while (!people.eof())  { //eof=end of file
    people>>yearborn;
    age=2014-yearborn;
    cout<<name<<"\t"<<age<<"\n"; //print each number
    people>>name; //read next name
    count++;
  } //while not end of file 
   people.close(); 
   cout<<count<<" people read\n";
 } //file opened successfully
 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 another way