I/O Stream <傻瓜机器人对话>

程序说明:如果 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值