C ++ getline doesn't seem to recognize newlines in input channels for stdin

This code:

$ cat junk.cpp

#include <stdio.h> #include <malloc.h> #include <iostream> #include <string> using namespace std; int main(int argc, char **argv) { string line; while(getline(cin, line)) { cout << line << endl; } return 0; } 

works fine if I run it, then type "hello" and "there

$ trash hello hello there

So far so good.

But I have another program:

$ cat junk1.c

 #include <stdio.h> int main(int argc, char **argv) { int i = 4; while(i--) { printf("abc\n"); sleep(1); } return 0; } 

This output prints 4 lines of "abc \ n" and sleeps after each line.

So, if I do this:

junk1 | junk

I would expect to see every line of "abc" followed by 1 second of sleep, but instead I see 4 seconds of sleep, followed by all 4 lines of "abc" at the end.

Obviously, getline () buffers all output from junk1 and only processes it when junk1 exits.

This is not the behavior I need because I want to pass stdout from a program that runs forever and produces voluminous output to a program such as junk.cpp.

Any idea what is going on here?

Thanks!

+5
source share
1 answer

This is probably due to the fact that stdout in junk1.c buffered: all entries in it (via printf or any other means) are collected in the buffer in memory and written only to stdout when the program exits.

To force stdout actually write what it has in the buffer, you should use flush (in your case, you should use it after each printf ).

+3
source

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


All Articles