Files

Another way to read from file

The program also below reads the same file with a name and year born, but it reads it in as a string and then separates the string into name and yearborn.

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
30
31
//Read in name and year born from a file as a sting
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
   string name,input,yearString;
   int yearborn, age,count=0;
   int currentYear=2016;
   ifstream people("c:/mycpp/names2.txt"); //input file stream
   if(people) { //file was opened
      cout<<"NAME\tAGE\n";  //heading
      while(getline(people,input)) { //Example: input="Jay,1994" 
         int p=input.find_first_of(","); //Example: p=3 
         if(p<0) cout<<"Error: "<<input<<endl;
         else {
            name=input.substr(0,p); //Example: name="Jay"
            yearString=input.substr(p+1); // Example: yearString="1994"
            yearborn=stoi(yearString); //stoi=String To Int, Example yearBorn=1994
            age=currentYear-yearborn;
            cout<<name<<"\t"<<age<<"\n"; //print each number
            count++;
         }//there was a comma
      }//each line
      people.close(); 
      cout<<count<<" people read\n";
   } //file opened successfully
   else  cout<<"File error\n"; //cout is used to notify user of error 
   system("pause");
   return 0;
} //main 
CODE

The input file has a name and the year born for each person separated by a comma, with one person on each line.

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

output
Please note the following:

In this program we use getline to read the entire line as a string. We look for the first space. Everything before the space is the name. We must convert the second part of the string into an int.

NEXT: Copy console to file