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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With