-1

i am trying to print 10 lines from a text file, and print another 10 based on user input or stop. My code print 10 lines but the first line is blank each time.

cin>>input;

ifstream file("midterm.txt");

while(input != sentinel && file >> output ) {
    for(int i = 0; i < 10; i++) {
        getline(file, output);
        cout<<output<<endl;
    }

    cout<<"\nEnter any key to continue reading, enter # to stop"<<endl;
    cin>>input;
}

file.close();
cout<<"File End";
return 0;
JaMiT
  • 9,693
  • 2
  • 12
  • 26
James P
  • 13
  • 3
  • 2
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Algirdas Preidžius Mar 13 '20 at 16:55
  • OK. Spotted the extra formatted extraction. I don't think you want `file >> output` at all. It doesn't seem to add anything to the program that testing the stream state with `file` wouldn't. You're better off testing the `getline` for success and exiting. – user4581301 Mar 13 '20 at 17:23
  • I made the adjustment, but the code still ignores the first line of the file. The file contains "one two three four five six seven eight nine ten one two three ..." each word on their individual line. The output is "two three four...one" if the user continues the next output will be "three four five....one two" and so on. The link Algirdas provided was a a little different from my problem. ios::ate just end the program with no output – James P Mar 15 '20 at 05:18

1 Answers1

0

In your code, you should add ios::ate to make the lines working and you should also show what type are the used variables. Try that:

string input;

string sentinel = "#";

string output;

cin>>input;

ifstream file("midterm.txt",ios::ate);

while(input != sentinel && file >> output ) {
    for(int i = 0; i < 10; i++) {
        getline(file, output);
        cout<<output<<endl;
    }

    cout<<"\nEnter any key to continue reading, enter # to stop"<<endl;
    cin>>input;
}

file.close();
cout<<"File End";
return 0;
Léolol DB
  • 145
  • 12