8

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?

Community
  • 1
  • 1
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • If your question is about C (and not about using stdio in C++), please tag it with C and not C++. – Mat Aug 26 '12 at 12:20
  • 2
    I've added tag C but this question is about C and C++ IO comparison, so i would like to keep C++ tag also. – FrozenHeart Aug 26 '12 at 12:22
  • Oh, it's been a while since a question here sparked my interest. I had never really payed attention to `tie`, I'll be watching this :) – Matthieu M. Aug 26 '12 at 12:35

2 Answers2

4

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?

Community
  • 1
  • 1
d99kris
  • 425
  • 4
  • 8
3

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.

phsym
  • 1,364
  • 10
  • 20