从C ++文件中打印一定数量的行

问题描述 投票:-1回答:1

我正在尝试从文本文件中打印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;
c++ ifstream
1个回答
0
投票

在您的代码中,应添加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;
© www.soinside.com 2019 - 2024. All rights reserved.