我试着打开一个文件,一次显示20行,直到文件结束,然后关闭程序。真实的简单。
代码如下:
int main()
{
using namespace std;
//try catch block sets up exception handling for files that do not exist. I added a few different
//text files to search for
try {
//intro message and prompt for file name
cout << "Welcome to the Advanced File I/O program." << endl;
cout << "Please enter the name of the text file you would like to search for: ";
string input;
cin >> input;
//concatonate input with .txt file designation
string fileName = input + ".txt";
fstream myFile;
//open the file and read it in
myFile.open(fileName, ios::in);
//if the file exists
if (myFile.is_open()) {
string line;
//while there are lines to be read in
while (getline(myFile, line)) {
//display 20 at a time
for (int i = 0; i < 20 && getline(myFile, line); i++) {
cout << line << endl;
}
//app console controle
system("pause");
system("cls");
}
//app console controle
system("pause");
system("cls");
//close the file once it's all read in and display end message
myFile.close();
system("cls");
cout << "You have reached the end of the text file. " << endl;
cout << "Thank you for visiting! Goodbye!" << endl;
system("pause");
exit(0);
}
//if the file does not open (does not exist) throw the error exception and close the program
else if (myFile.fail()) {
throw exception("File does not exist. Closing Program.");
cout << endl;
system("cls");
exit(0);
}
}
//catch the exception and display the message
catch (exception& e) {
cout << "\nError caught!" << endl;
cout << e.what();
}
}
问题是每次在for
循环中,它都会跳过输出的第一行。我很确定这是发生的,因为我调用了getline()
两次。但是,我不知道如何解决这个问题。
对于那些要告诉我不要使用using namespace std;
的人,我是这个作业所在课程的要求。
2条答案
按热度按时间7xzttuei1#
我只需要在while循环中的初始getline()调用之后打印该行。
evrscar22#
外层
while
循环从文件中阅读一行并丢弃它而不显示它,然后内层for
循环读取接下来的20行并显示它们,然后外层while
循环的下一次迭代读取并丢弃下一行,依此类推。请尝试以下内容: