且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反复从标准输入读到EOF

更新时间:2023-11-17 23:22:28

您采用的方法行不通-当'cin'在您所使用的上下文中为您提供文件结尾时,然后进行cin已关闭.

The approach you're taking there won't work - when 'cin' gives you end-of-file in the context you're using, then cin is closed.

出于您声明的目的,即先读取文本直到eof,然后再做一次",对于您以前错过的细微差别,我们深表歉意,但是如果您克隆标准输入文件描述符,然后使用克隆,您可以继续从这些其他文件描述符中进行读取.

For your stated purpose of "reading text until eof, then doing it again", sorry for missing the nuance of this previously, but if you clone the stdin file descriptor and then use the clone, you can continue reading from these additional file descriptors.

克隆iostream并不容易.请参阅如何从POSIX文件描述符构造c ++ fstream?

Cloning iostreams isn't easy. See How to construct a c++ fstream from a POSIX file descriptor?

这有点像c,但是这段代码将耗尽stdin的一个副本,直到该stdin关闭,然后将创建一个新副本并清空它,然后继续.

It's a little c-like, but this code will drain one copy of stdin until that stdin closes, then it'll make a new copy and drain that, and on.

#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";
    }
}