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?

3
  • If your question is about C (and not about using stdio in C++), please tag it with C and not C++. Commented Aug 26, 2012 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. Commented Aug 26, 2012 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 :) Commented Aug 26, 2012 at 12:35

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.