Arrays

Read a file into an array

The program below will read a plain text file as shown below:

Jay 1994
Debbie 1976
John 1988
Greg 1954
Carol 1999
Sam 2000
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//Read file of name and year born. Print name and age
#include <fstream>
#include <iostream>
#include<string>
#include<ctime>
using namespace std;
int currentYear() {
	return time(0) / 60 / 60 / 24 / 365 + 1970;
} //currentYear

int readfile(ifstream &people,string names[],int years[])
{ int count=0;
  people>>names[count]; //read first before loop! 
  while (!people.eof() && count<20) { //eof=end of file
     people>>years[count];
     count++;
     if (count<20) people>>names[count]; //read next name
  } //while not end of file
  people.close();
  return count;
} //readfile

void printAll(string names[],int years[], int count) {
  int age;
  int year=currentYear(); //call it just once!
  cout<<"NAME\tAGE\n";
  for(int i=0; i<count; i++) {
    age=year-years[i];  
    cout<<names[i]<<"\t"<<age<<"\n"; 
  } //for loop
} //printAll

int main(void) {
   ifstream names;  //input file stream
   string people[20]; //allow 20 names 
   int year[20]; //yearborn for same 20 people
   int numPeople; //number of people, there may be less than 20
   names.open("c:/mycpp/names.txt"); //associates the name inch with a file
   if (names.fail()) //maybe C is full, write protected, etc.
     cout<<"File not found\n"; //cout is used to notify user of error
   else 
   {  numPeople=readfile(names, people,year);
      printAll(people, year, numPeople);
   } //read file and print
   system("pause");
   return 0;
} //main
CODE
Output:
Name     Age
Jay 20
Debbie 38
John 26
Greg 60
Carol 15
Sam 14

You can learn more about the time in the lesson on structures.

NEXT: Employee program project