0

Hello I am a newbie on C++. And I wish to know what is casing problem in the following code.

int MAX = 15;
while (!inputfile.eof()){
    getline(inputfile, name);
    cout << name << endl;
    for (int i = 0; i < MAX; i ++){
        inputfile >> questionnumber >> answer;
        cout << questionnumber << "  " << answer << "\n";
    }
    //inputfile.ignore(); #This will ignore the Enter key in Buffer zone
    //inputfile.sync(); #But how come this can't clean the Enter key in Buffer zone?
}

the datas inside inputfile are

key
 2 B
13 D
 3 C
 5 D
14 C
 6 C
 8 A
15 B
 9 A
 1 A
 7 B
10 B
11 C
 4 D
12 D
 0 James

Sorry for my poor English and I don't know how to describe this kind of problems.

Thanks.

KutengF
  • 41
  • 5
  • 2
    Have a look at this question: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons I don't know if it's actually your problem, but you should read it. – wychmaster Apr 28 '20 at 10:41
  • Thanks I've learnt a lot, never thought of eof as loop condition will be a problem. – KutengF Apr 28 '20 at 11:09
  • Does this answer your question? [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Azeem Apr 28 '20 at 11:33
  • @Azeem Sorry, maybe half? Now I know what's causing the infinite loop, but I still want to know why "inputfile >> questionnumber >> answer;" is always getting "0 J" instead of "0 James" or other strings – KutengF Apr 28 '20 at 11:58
  • And I wish to know what char "inputfile.ignore();" is ignoring. – KutengF Apr 28 '20 at 12:01
  • @KutengF: Here's an [example](https://godbolt.org/z/3MSQkm) that might be helpful for you. Also, you need to show your full code including all the declarations for the variables being used in your code snippet. See [std::fstream::ignore](https://en.cppreference.com/w/cpp/io/basic_istream/ignore) here. – Azeem Apr 28 '20 at 12:15

0 Answers0