I'm using Eclipse to code in C/C++ and I'm struggling with what might be something pretty easy. In my code below I use printf()
and after scanf()
. Althougth printf
is written before scanf()
the output differs. I was able to find out something about similar issue here. But I wasn't able to solve it. Any ideas?
Code:
#include <stdio.h> int main() { int myvariable; printf("Enter a number:"); scanf("%d", &myvariable); printf("%d", myvariable); return 0; }
Expected output:
Enter a number:1 1
Instead I get:
1 Enter a number:1
"printf is written before scanf()". it's not what you put in the code.
Your printf s and scanf s are executed in order. The output looks messed up because of buffering. When "power:" gets printed, it ends up in the buffer that does not get flushed until a number gets entered. Adding \n solves this for console output.
Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.
When you call printf , each of its arguments is evaluated and the result is passed to the function. In this case, evaluation involves calling the scanf function. The value returned by scanf is then passed to printf .
Your output is being buffered. You have 4 options:
explicit flush
fflush
after each write to profit from the buffer and still enforce the desiredbehavior/display explicitly.
fflush( stdout );
have the buffer only buffer lines-wise
useful for when you know that it is enough to print only complete lines
setlinebuf(stdout);
disable the buffer
setbuf(stdout, NULL);
disable buffering in your console through what ever options menu it provides
Here is your code with option 1:
#include <stdio.h> int main() { int myvariable; printf("Enter a number:"); fflush( stdout ); scanf("%d", &myvariable); printf("%d", myvariable); fflush( stdout ); return 0; }
Here is 2:
#include <stdio.h> int main() { int myvariable; setlinebuf(stdout); printf("Enter a number:"); scanf("%d", &myvariable); printf("%d", myvariable); return 0; }
and 3:
#include <stdio.h> int main() { int myvariable; setbuf(stdout, NULL); printf("Enter a number:"); scanf("%d", &myvariable); printf("%d", myvariable); return 0; }
Ok, so finally I used something similar to what @zsawyer wrote as an option labelled 3. In my code I inserted this line:
setvbuf(stdout, NULL, _IONBF, 0);
As a first line in main():
#include <stdio.h> int main() { setvbuf(stdout, NULL, _IONBF, 0); int myvariable; printf("Enter a number:"); scanf("%d", &myvariable); printf("%d", myvariable); return 0; }
I got it from here.
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