stdout和stdin的关系

时间:2012-08-26 12:09:39

标签: c++ c

  

可能重复:
  Does reading from stdin flush stdout?

C ++ Standard保证在下次调用std :: cin之前打印缓冲区中包含的所有数据。像这样:

#include <iostream>

void bar()
{
    int x;
    std::cout << "Enter an integer: "; /* 1 */
    std::cin >> x; /* 2 */
}

因此:

ISO / IEC 14882:2011

  

27.4.2窄流对象[narrow.stream.objects]

     

2初始化对象cin后,cin.tie()返回&amp; cout。它的   state与basic_ios :: init相同   (27.5.5.2)。

     

27.4.3宽流对象[wide.stream.objects]

     

2初始化对象wcin后,wcin.tie()返回&amp; wcout。   其状态与其他情况相同   basic_ios :: init(27.5.5.2)。

但在C中,实际上并不能保证stdout缓冲区中包含的所有内容都会在尝试stdin之前打印出来吗?

#include <stdio.h>

void bar()
{
    int x;
    printf("Enter an integer: "); /* 1 */
    scanf("%d", &x); /* 2 */
}

我知道stdout是行缓冲但我不想在这种情况下放置'\ n'字符。使用fflush / fclose / etc是在C中输入请求之前获得输出的唯一正确方法吗?

2 个答案:

答案 0 :(得分:4)

不,没有这样的保证。 是的,你可以使用fflush()来确保刷新stdout。

这个问题密切相关:Does reading from stdin flush stdout?

答案 1 :(得分:3)

我不知道C ++中的cin / cout关系,谢谢。 在C中,我不知道刷新stdout缓冲区的其他方法。当我需要确保在给定时间打印输出时,我总是使用 fflush