вывести определенное количество строк из файла в C ++ - PullRequest
0 голосов
/ 13 марта 2020

Я пытаюсь напечатать 10 строк из текстового файла и напечатать еще 10 строк на основе ввода или остановки пользователя. Мой код печатает 10 строк, но первая строка каждый раз пуста.

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;

1 Ответ

0 голосов
/ 13 марта 2020

В вашем коде вы должны добавить ios::ate, чтобы линии работали, и вы также должны показать, какой тип используются переменными. Попробуйте это:

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