简体   繁体   中英

order of printf command in c

I am trying to learn c and am just starting with watching some online videos and was trying to do this example but my results are not what I expect. This code is simply to enter a number and print out the number you entered, however I can't tell where it is going wrong.

 #include <stdio.h>

int main(void) {
    int aNumber;
    printf("Please enter a number: ");
    scanf("%d", &aNumber);
    printf("you entered %d", aNumber);
    getchar();
    return 0;
}

but when I run this code it should ask the user to enter a number instead it does nothing until i enter a number and the output is this:

5
Please enter a number: you entered 5

where I type in 5, press enter and then the code prints out the statement. Can anyone tell me why the ordering is going wrong. It should be

Please enter a number: 5
you entered 5

where the "please enter a number: " pops up first then I enter 5 and so on.

You most likely need to flush stdout to make the output show up. To do this call fflush(stdout) . If you don't do this some of the output could be buffered which causes what you are seeing.

#include <stdio.h>

int main(void) {
    int aNumber;
    printf("Please enter a number: ");
    fflush(stdout);
    scanf("%d", &aNumber);
    printf("you entered %d", aNumber);
    getchar();
    return 0;
}

That´sa really unusual result from such a simple program. Other people pointed out the ´fflush´, I just want to mention that ending printf with a new line also cause the buffer to flush out. so if you don´t care your input to appear one a new line, you have new way to deal with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM