程序说明:如果 kingLear.txt 行与行之间有单个或多个空行,则忽略空行内容,继续向下读取文件内容并显示。
不论文件末尾最后一行有无换行符程序均可正常运行。
kingLear.txt
Is not this your son, my lord?
I cannot conceive you.
I cannot wish the fault undone, the issue of it being so proper.
I must love you, and sue to know you better.
Come not between the dragon and his wrath;
I lov’d her most, and thought to set you rest on her kind nursery.
Whom I have ever honor’d as my king,
Lov’d as my father, as my master follow’d,
As my great patron thought on in my prayers.
运行结果:
Enter your question: 1
1
Is not this your son, my lord?
Enter your question: 2
2
I cannot conceive you.
Enter your question: 3
3
I cannot wish the fault undone, the issue of it being so proper.
Enter your question: 4
4
I must love you, and sue to know you better.
Enter your question: 5
5
Come not between the dragon and his wrath;
Enter your question: 6
6
I lov’d her most, and thought to set you rest on her kind nursery.
Enter your question: 7
7
Whom I have ever honor’d as my king,
Enter your question: 8
8
Lov’d as my father, as my master follow’d,
Enter your question: 9
9
As my great patron thought on in my prayers..
Enter your question: 10
10
Is not this your son, my lord?
Enter your question:
test.cpp
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
bool readLine(istream& fin = cin);
int main() {
ifstream fin;
fin.open("/Users/br/Documents/C:C++/Test/Test/kingLear.txt");
if (fin.fail()) {
cout << "fin file opening failed.";
exit(EXIT_FAILURE);
}
while (true) {
readLine();
while (readLine(fin)) {
if (! fin.eof())
continue;
else {
fin.close();
fin.open("/Users/br/Documents/C:C++/Test/Test/kingLear.txt");
readLine(fin);
break;
}
}
}
return 0;
}
bool readLine(istream& fin) {
char c;
fin.get(c);
if (c == '\n')
return true;
while (c != '\n' && (! fin.eof())) {
cout << c;
fin.get(c);
}
cout << "\n";
return false;
}