Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdout and stdin relationships [duplicate]

Tags:

c++

c

Possible Duplicate:
Does reading from stdin flush stdout?

C++ Standard guarantees that all data contained in the buffer will be printed before next call to std::cin. Like this:

#include <iostream>

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

Because of this:

ISO/IEC 14882:2011

27.4.2 Narrow stream objects [narrow.stream.objects]

2 After the object cin is initialized, cin.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2).

27.4.3 Wide stream objects [wide.stream.objects]

2 After the object wcin is initialized, wcin.tie() returns &wcout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2).

But in C there are really no guarantees that everything contained in the stdout buffer will be printed before any attempt to stdin?

#include <stdio.h>

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

I know that stdout is line buffered but i don't want to put '\n' character in such situations. Is using fflush / fclose / etc is the only right way to get output right before input request in C?

like image 785
FrozenHeart Avatar asked Aug 26 '12 12:08

FrozenHeart


2 Answers

No, there are no such guarantees. Yes, you may use fflush() to ensure that stdout is flushed.

This question is closely related: Does reading from stdin flush stdout?

like image 154
d99kris Avatar answered Nov 15 '22 18:11

d99kris


I didn't know the cin / cout relation in C++, thank you. In C, I don't know other way to flush the stdout buffer. I always use fflush when I need to be sure that the output has been printed at a given time.

like image 38
phsym Avatar answered Nov 15 '22 16:11

phsym