Hieu Nguyen
Hieu Nguyen

Reputation: 1517

Read file in C++

I wrote the following code to read the content of a file:

#include <ifstream>
#include <iostream>
using namespace std;

int main(){
    char file_name[30] = "data.txt";
    // Create an ifstream to read the file.
    ifstream People_in(file_name);
      while (1) {
        if (People_in.eof())
            break;
        People_in >> first_name >> last_name >> age;
        cout << endl << "First Name: " << first_name;
        cout << endl << "Last Name:  " << last_name;
        cout << endl << "Enter Age:  " << age;
        cout << endl;

      }
      People_in.close();
      return 0;
  }

data.txt content:

FirstName1
LastName1
1
FirstName2
LastName2
2
FirstName3
LastName3
3

The output I expected:

First Name: FirstName1
Last Name: LastName1
Age: 1

First Name: FirstName2
Last Name: LastName2
Age: 2

First Name: FirstName3
Last Name: LastName3
Age: 3

But the output is:

First Name: FirstName1
Last Name: LastName1
Age: 1

First Name: FirstName2
Last Name: LastName2
Age: 2

First Name: FirstName3
Last Name: LastName3
Age: 3

First Name: FirstName3
Last Name: LastName3
Age: 3

I can't figure out why? PeopleIn is supposed to reach eof when it read through all the data. But how can it repeat the last 3 line ??

Upvotes: 2

Views: 667

Answers (4)

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11088

This is because after last step the eof is not reached (there is character after 3 in your file).

Try this:

while (People_in >> first_name >> last_name >> age)
{
    cout << endl << "First Name: " << first_name;
    cout << endl << "Last Name:  " << last_name;
    cout << endl << "Enter Age:  " << age;
    cout << endl;
}

Upvotes: 3

zad
zad

Reputation: 3415

try it like this

  while (People_in) {
//... 
}

remove the if break part

Upvotes: 0

Chris
Chris

Reputation: 2896

Even without the newline at the end of the file, the code will still print extra input. Instead, after you read in the first name, last name in age, try:

People_in >> first_name >> last_name >> age;
if (first_name.length() == 0)
    break;
....

Upvotes: 0

Ajay
Ajay

Reputation: 18411

Check that there is no extra new lines at the end of file. It seems there is extra set of new lines (\n), and it is causing eof method to fail.

Upvotes: 0

Related Questions