Vectors

This program reads a file into a vector. Unlike arrays, vectors are not passed by reference unless we include the &.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//Read in name and year born from a file into a vector
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
const int currentYear=2016;
void getFile(vector<string> &names,vector<int> &yearBorn) {
  string input,yearString;
  ifstream people("c:/mycpp/names2.txt"); //input file stream
  if(people) { //file was opened
    while(getline(people,input)) { //Example: input="Jay 1994" 
      int p=input.find_first_of(","); //Example: p=3 
      if(p>=0) {
        names.push_back(input.substr(0,p)); //Example: name="Jay"
        yearString=input.substr(p+1); // Example: yearString="1994"
        yearBorn.push_back(stoi(yearString)); //stoi=String To Int, Example yearBorn=1994
      }//there was a comma
    }//each line
    people.close(); 
  }
}//getFile

void showAll(vector<string> names,vector<int> yearBorn) {
  cout<<"NAME\tAGE\n";
  int count=names.size();
  for(int i=0;i<count;i++) {
    int age=currentYear-yearBorn[i];
    cout<<names[i]<<"\t"<<age<<endl;
  }//for
}//showAll

int search(vector<string> names, string name) {
  int found=-1;
  int i=0;
  while(found<0 && i<names.size()) {
    if(names[i]==name) found=i;
    i++;
  }//while not found and more names
  return found;
}//search

int main(void) {
  vector<string> names;
  vector<int> yearBorn;
  string lookfor;
  getFile(names,yearBorn);
  showAll(names,yearBorn);
  if(names.size()==0) cout<<"There was an error reading the file.\n";
  else {
    cout<<names.size()<<" people read\n";
    cout<<"Enter the name of the person you are looking for:";
    getline(cin,lookfor);
    int pos;
    pos=search(names,lookfor);
    if(pos>=0) cout<<lookfor<<" was born in "<<yearBorn[pos]<<endl;
    else cout<<lookfor<<" was not found.\n";
  } //names read
  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.

NEXT: Read a file and bubble sort