簡體   English   中英

反復從標准輸入讀到EOF

[英]Repeatedly reading to EOF from stdin

我希望程序從stdin讀取到EOF,然后打印所有輸入並重復。 我嘗試清除stdin的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,然后再做一次”的目的,對於以前錯過的細微差別,我們深感抱歉,但是如果克隆stdin文件描述符然后使用克隆,則可以繼續從這些其他文件描述符中進行讀取。

克隆iostream並不容易。 請參閱如何從POSIX文件描述符構造c ++ fstream?

它有點像c,但是這段代碼將清空stdin的一個副本,直到該stdin關閉,然后再創建一個新副本並清空它,然后繼續。

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

那是因為你有printf(“ begin”); 在循環中,這樣您就可以在每次循環時再次打印它。

循環不會等待輸入,因此每次它從stdin中讀取數據時-如果沒有任何內容,它將立即獲得EOF,因此繼續循環直到存在某些數據。

讓我知道這是否沒有道理-還是我完全理解錯了。

例如:

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

using namespace std;

int main() {

  cin >> noskipws;

  printf("Begin");

  while (1) {

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

  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM