Reading data from a text file.

Each line of the text file has first name, last name, and a salary. Something along the lines of this:

john doe 4000
bob miller 9000

I want my program to take the first name, last name, and salary of each line and assign them to strings. I have tried this so far:
1
2
3
4
5
6
7
8
9
while (inFile){
        
        inFile >> firstName;
        inFile >> lastName;
        inFile >> grossPay;
        
        cout << firstName << " " << lastName << " " << grossPay << endl;
    }


When it outputs the names and the salary, the last line of the text file gets output twice by the program.
Last edited on
Mimmick this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}


Source - http://www.cplusplus.com/doc/tutorial/files/
Topic archived. No new replies allowed.