我正在尝试从文本文件中打印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;
在您的代码中,应添加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;