简体   繁体   English

C中printf命令的顺序

[英]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. 我正在尝试学习c,并且只是从观看一些在线视频开始,并试图做这个例子,但是我的结果不是我期望的。 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 5
Please enter a number: you entered 5 请输入数字:您输入了5

where I type in 5, press enter and then the code prints out the statement. 在其中键入5的位置,按Enter键,然后代码将打印出该语句。 Can anyone tell me why the ordering is going wrong. 谁能告诉我为什么订购错了。 It should be 它应该是

Please enter a number: 5 请输入数字:5
you entered 5 您输入了5

where the "please enter a number: " pops up first then I enter 5 and so on. 首先弹出“请输入数字:”,然后输入5,依此类推。

You most likely need to flush stdout to make the output show up. 您很可能需要刷新stdout才能显示输出。 To do this call fflush(stdout) . 为此,请调用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. 其他人指出了“ fflush”,我只想提及以新行结尾的printf也会导致缓冲区被冲洗掉。 so if you don´t care your input to appear one a new line, you have new way to deal with it. 因此,如果您不希望输入内容出现在新行中,则可以使用新方法来处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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