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

45,101

Solution 1

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

Solution 2

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.

Share:
45,101
quapka
Author by

quapka

Master's degree in Information Technology Security, Masaryk University in Brno, in the Czech Republic. Bachelor's degree in Mathematics at Faculty of Science, Masaryk University in Brno. Tweet me!: https://twitter.com/quapka Or if you'd like to be more business-like: https://www.linkedin.com/pub/jan-kvapil/97/453/65b Previous projects: Git: https://github.com/JendaPlhak/math_in_python/tree/master/KvagrsWork

Updated on May 31, 2020

Comments

  • quapka
    quapka about 4 years

    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