简体   繁体   English

c ++ getline似乎没有识别输入到stdin的输入中的换行符

[英]c++ getline does not seem to recognize newlines in input piped to stdin

This code: 这段代码:

$ cat junk.cpp $ 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 "hi" and "there 如果我运行它工作正常,然后键入“hi”和“那里

$ junk hi hi there there $ junk你好那里

So far so good. 到现在为止还挺好。

But I have another program: 但我有另一个程序:

$ cat junk1.c $ 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 one outputs 4 lines of "abc\\n" and sleeps after each line. 这一行输出4行“abc \\ n”并在每行之后休眠。

So if I do this: 所以,如果我这样做:

junk1 | junk1 | junk 破烂

I would expect to see each line of "abc" followed by a 1 second sleep, but instead I see 4 seconds of sleep followed by all 4 "abc" lines at the end. 我希望看到“abc”的每一行后面都会有1秒的睡眠,但我会看到4秒的睡眠,然后是最后的4条“abc”线。

Apparently getline() is buffering all output from junk1, and only proceding when junk1 terminates. 显然,getline()正在缓冲junk1的所有输出,并且仅在junk1终止时进行处理。

This is not the behavior I need, because I want to pipe the stdout from a program that runs forever and produces voluminous output, to a program like junk.cpp. 这不是我需要的行为,因为我想将stdout从一个永远运行并产生大量输出的程序传送到像junk.cpp这样的程序。

Any idea what is going on here? 知道这里发生了什么吗?

Thanks! 谢谢!

This is probably caused by stdout in junk1.c being buffered: all writes to it (by printf or any other means) are collected in an in-memory buffer, and only written to stdout when the program exits. 这可能是由缓冲的junk1.c中的stdout引起的:对它的所有写入(通过printf或任何其他方式)都收集在内存缓冲区中,并且只在程序退出时写入stdout

To force stdout to actually write what it has in the buffer, you have to use flush (in your case, you should use it after every printf ). 要强制stdout实际写入它在缓冲区中的内容,你必须使用flush (在你的情况下,你应该在每个printf之后使用它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM