反复从标准输入读到EOF [英] Repeatedly reading to EOF from stdin

查看:73
本文介绍了反复从标准输入读到EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like my program to read from stdin until EOF, print all input, and repeat. I tried clearing the EOF state of stdin as follows:

#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();

  }

}

但是,在接收并打印了第一个输入之后,程序将无限次打印"Begin",而无需等待进一步的输入.

After the first input is received and printed, however, the program just infinitely prints "Begin" without waiting for further input.

推荐答案

您采用的方法行不通-当'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";
    }
}

这篇关于反复从标准输入读到EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆