【问题标题】:Should I handle multiple instances of cin / stdin?我应该处理 cin / stdin 的多个实例吗?
【发布时间】:2023-01-18 22:53:18
【问题描述】:

下面是一个 C++ 小程序,它应该充当 cat linux binutil:它获取一个或多个输入,如命令行参数中详述(可能通过“-”指定标准输入)并将它们复制到标准输出。不幸的是,它显示了一种我无法理解的根本原因的意外行为......

根据以下命令

./ccat - test.text

我直接按了 CTRL-D,没有传递任何字符。我希望该程序无论如何都显示 test.txt 的内容,但相反,该程序退出时没有将任何更多字符传递到标准输出流。

关于我应该如何更正我的代码以在这种情况下具有正确行为的任何想法?我应该处理标准流的多个实例(cin、cout...)吗?如果是这样,您知道如何在 C++ 中实现这一点吗?

先感谢您。

/**** ccat.cpp ****/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char **argv) {
    if (argc <= 1) {
        cout << cin.rdbuf();
    } else {
        vector<string> inputs;
        for (int i=1; i<argc; ++i) inputs.push_back(argv[i]);

        for (auto &in: inputs) {
            if (in == "-" || in == "--") {
                cout << cin.rdbuf();
            }
            else {
                ifstream *fd = new ifstream(in);
                if (!fd->is_open()) cerr << "Cannot open file \'" << in << "\'\n";
                else cout << fd->rdbuf();
                delete fd;
            }
        }
    }

    return 0;
}

我依次尝试了以下命令:

$ ./ccat > test.txt
Let's try this text.
I would expect a correct behaviour.
$ ./ccat - test.txt # I hit CTRL-D directly without passing any character first
$ ./ccat - test.txt
But when I add some characters before hitting CTRL-D... This works fine.
But when I add some characters before hitting CTRL-D... This works fine.
Let's try this text.
I would expect a correct behaviour.

如示例所示,我希望在两种情况(最后两个 shell 提示)中的任何一种情况下 test.txt 都显示在标准输出上,但只有当我首先通过标准输入注入字符时才会发生这种情况。直接按 CTRL-D 会使程序提前退出。

【问题讨论】:

  • 不是你的(当前)问题:你不应该使用new来创建ifstream -> ifstream fd{in};
  • 您在 Ctrl-D 之前按了 Enter 键来运行命令,对吗?

标签: c++ cin cat


【解决方案1】:

那是超载 10 here

basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb );

它说

如果没有插入字符,则执行setstate(failbit)

也就是说,cout现在处于错误状态,不会输出任何东西。

正在做

cout.clear();

首先在 else 分支中应该这样做。

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2016-09-05
    • 2022-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多