Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

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

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...