Re-reading in EOF from stdin

I would like my program to read from stdin to EOF, print all the input, and repeat. I tried to clear 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(); } } 

After the first input is accepted and printed, the program simply endlessly prints "Start", without waiting for further input.

0
source share
2 answers

The approach you use will not work - when cin gives you the end of the file in the context you use, then cin closes.

For your stated purpose: “read the text until it repeats”, sorry for the lack of nuance of this earlier, but if you clone the stdin file descriptor and then use the clone, you can continue reading from these additional file descriptors.

Cloning iostreams is not easy. See How to build C ++ fstream from a POSIX file descriptor?

This is a bit like c-like, but this code flushes one copy of stdin until that stdin closes, then it makes a new copy and merge it further.

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

This is because you have printf ("begin"); inside your loop so you are going to print it every time in a loop.

The loop will not wait for input, so every time it reads data from stdin - if there is nothing there, it immediately receives EOF and therefore continues the loop until some data appears.

Let me know if this makes no sense - or if I am completely mistaken.

eg:

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

Source: https://habr.com/ru/post/975232/


All Articles