0

I am new to C++ and I am currently exploring things. Now I am on reading a text file. This is the code:

while (myfile.good()) {
        myfile >> tempNum;
        getline(myfile, tempName);
        getline(myfile, tempCourse);
        myfile >> tempTuition;
        if (myfile.eof()) break;
        Student temp(tempNum, tempName, tempCourse, tempTuition);
        students.push_back(temp);
    }

Now my file currently contains this:

201699856
Justin Chu
BSITDA
36889

Problem is, with my current code, it reads like this.

  • tempNum = 201699856
  • tempName = ""
  • tempCourse = "Justin Chu"
  • tempTuition = "BSITDA"

At tempTuition, my program freezes because it contains an invalid data. Why is the getline() skipping the 2nd line? And how can I fix the program to read correctly?

Micha Wiedenmann
  • 17,330
  • 20
  • 79
  • 123
Ryon
  • 23
  • 3
  • 3
    You loop is almost equivalent to `while(!myfile.eof())`, so please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Feb 26 '18 at 12:30
  • Also see [How does reading file with while loops work in C++?](https://stackoverflow.com/q/14009737/608639) and [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/q/5605125/608639) – jww Feb 26 '18 at 12:38
  • Thanks for the links. So I saw that you can chain the input like while(stream>>variable>>variable). But how will it work for variables that has an int and a string? String when read, gives a single word with no whitespace. – Ryon Feb 27 '18 at 09:15

1 Answers1

0

From std::getline:

When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.

Arnav Borborah
  • 9,956
  • 4
  • 32
  • 69
zteffi
  • 598
  • 4
  • 16