簡體   English   中英

c ++ getline似乎沒有識別輸入到stdin的輸入中的換行符

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

這段代碼:

$ 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;
}

如果我運行它工作正常,然后鍵入“hi”和“那里

$ junk你好那里

到現在為止還挺好。

但我有另一個程序:

$ cat junk1.c

#include <stdio.h>

int
main(int argc, char **argv)
{
    int i = 4;

    while(i--)
    {
        printf("abc\n");
        sleep(1);
    }

    return 0;
}

這一行輸出4行“abc \\ n”並在每行之后休眠。

所以,如果我這樣做:

junk1 | 破爛

我希望看到“abc”的每一行后面都會有1秒的睡眠,但我會看到4秒的睡眠,然后是最后的4條“abc”線。

顯然,getline()正在緩沖junk1的所有輸出,並且僅在junk1終止時進行處理。

這不是我需要的行為,因為我想將stdout從一個永遠運行並產生大量輸出的程序傳送到像junk.cpp這樣的程序。

知道這里發生了什么嗎?

謝謝!

這可能是由緩沖的junk1.c中的stdout引起的:對它的所有寫入(通過printf或任何其他方式)都收集在內存緩沖區中,並且只在程序退出時寫入stdout

要強制stdout實際寫入它在緩沖區中的內容,你必須使用flush (在你的情況下,你應該在每個printf之后使用它)。

暫無
暫無

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

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