我希望我的程序从 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/