使用scanf()输入问题

我是C的新手,所以我在使用scanf()时遇到了一些麻烦。

#include  #include  int main() { int height; int weight; printf("Enter height in inches:\n"); scanf("%d", &height); printf("Enter weight in pounds:\n"); scanf("%d", &weight); printf("You are %d inches tall and weigh %d pounds.", height, weight); return 0; } 

我很确定这是正确的语法,但是当我运行它时,它显示一个空屏幕,在我输入2个数字后,它显示:

64

120

以英寸为单位输入高度

以磅为单位输入重量:

你身高64英寸,体重120磅。

根据一些教程,在我输入第二个数字之前,它应该显示“以英寸为单位输入高度:”,然后输入第一个数字和“以磅为单位输入重量:”。 请帮我!

我正在使用Eclipse编写程序,MinGW作为编译器,如果相关的话。

这是eclipse中的一个错误,大多数人都使用eclipse和MinGW进行了报道。

要解决此问题,您可以在每次调用printf后使用fflush(stdout)或在main的开头使用以下内容:

 setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); 

这将导致stdoutstderr在写入时立即刷新。

尝试使用scanf_s而不是scanf,我只是运行它,它工作。

我建议你使用sscanf insted of scanf并将fgets添加到顶部会更加逻辑。

这将是:

 int height; char buffer[32]; /*Add this to collect you data*/ printf("Enter height in inches:\n"); fgets(buffer,sizeof(buffer),stdin); /*Add this line to get value from keyboard*/ sscanf(buffer,"%d", &height); /*Change scanf to sscanf*/ 

和另一个一样

我建议在Windows上使用Putty,或者在Mac OSX上使用命令行。 使用“Wal Werror”编译器

是的,您需要等待它在输入数字之前显示输出。

例如,运行程序时出现此行

 Enter height in inches: 

然后进入

  64 

然后出现这个

 Enter weight in pounds: 

然后输入

  120 

那么输出应该如预期的那样