开发者

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 ??


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;
}


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.


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;
....


try it like this

  while (People_in) {
//... 
}

remove the if break part

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜