c++ - 从 stdin 重复读取 EOF

标签 c++ io

我希望我的程序从 stdin 读取直到 EOF,打印所有输入,然后重复。我尝试如下清除标准输入的 EOF 状态:

#include <string>
#include <iostream>
#include <iterator>

using namespace std;

int main() {

  cin >> noskipws;

  while (1) {

    printf("Begin");
    istream_iterator<char> iterator(cin);
    istream_iterator<char> end;
    string input(iterator, end);
    cout << input << endl;
    cin.clear();

  }

}

然而,在收到并打印第一个输入后,程序只是无限打印“开始”,而不等待进一步的输入。

最佳答案

您在那里采用的方法将行不通 - 当“cin”在您正在使用的上下文中为您提供文件结尾时,cin 将关闭。

对于您声明的“读取文本直到 eof,然后再读一次”的目的,很抱歉之前错过了这个的细微差别,但是如果您克隆标准输入文件描述符然后使用克隆,您可以继续阅读这些额外的文件描述符。

克隆 iostream 并不容易。参见 How to construct a c++ fstream from a POSIX file descriptor?

它有点像 C,但这段代码会耗尽标准输入的一个拷贝,直到该标准输入关闭,然后它会制作一个新拷贝并耗尽它,等等。

#include <iostream>
#include <string>

void getInput(std::string& input)
{
    char buffer[4096];
    int newIn = dup(STDIN_FILENO);
    int result = EAGAIN;
    input = "";
    do {
        buffer[0] = 0;
        result = read(newIn, buffer, sizeof(buffer));
        if (result > 0)
            input += buffer;
    } while (result >= sizeof(buffer));
    close(newIn);

    return input;
}

int main(int argc, const char* argv[])
{
    std::string input;
    for (;;) {
        getInput(input);
        if (input.empty())
            break;
        std::cout << "8x --- start --- x8\n" << input.c_str() << "\n8x --- end --- x8\n\n";
    }
}

关于c++ - 从 stdin 重复读取 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749982/

相关文章:

python - 如何终止正在运行的 iPython 进程

c - C 中读取文件不清楚

c++ - 1.50 中的 boost::shared_mutex 问题

python - pybind11 STL 自动转换器破坏 std::list 指针

c++ - NaN 何时不在 C++ 中传播?

java - 如何避免在 Java 和 native C++ 代码之间复制数据

c++ - 是否有任何中间件/库可以将您的二进制或文本数据从 64 位转换为 32 位?

arrays - 将文件中的行复制到 char *array[]?

python - 如何在 Python3 中使用 StringIO?

ios - iOS 和 OSX 文件字符的区别