C/C++ printf() before scanf() issue

流过昼夜 提交于 2019-11-26 11:16:15

Your output is being buffered. You have 4 options:

  1. explicit flush

    fflush after each write to profit from the buffer and still enforce the desiredbehavior/display explicitly.

    fflush( stdout );
    
  2. have the buffer only buffer lines-wise

    useful for when you know that it is enough to print only complete lines

    setlinebuf(stdout);
    
  3. disable the buffer

    setbuf(stdout, NULL);
    
  4. disable buffering in your console through what ever options menu it provides


Examples:

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.

Fast and painless, I've just defined a macro named "eprint" to add a flush() after calling printf(...) and I just use the eprint macro below:

#define eprintf(...) printf(__VA_ARGS__); \
                 fflush(stdout);      \

Sample code here:

#include <stdio.h>
#include <stdlib.h>

#define eprintf(...) printf(__VA_ARGS__); \
                     fflush(stdout);      \

int main(void) {
    int a;

    eprintf("a=");

    scanf("%d",&a);

    eprintf("I've read value %d.\n",a);

    return EXIT_SUCCESS;
}

Eclipse console output:

a=5
I've read value 5.

PS: I've just wasted 30 minutes looking up this eclipse console issue and possible fixes, and this one seems to be the most straight forward and easy to understand for anyone looking for such a thing.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!