简体   繁体   English

使用scanf()输入时出现问题

[英]Trouble with input using scanf()

I'm new to C so I'm having a bit of trouble with scanf(). 我是C语言的新手,所以scanf()有点麻烦。

#include <stdio.h>
#include <stdlib.h>

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

I'm pretty sure this is the correct syntax but when I run it, it shows an empty screen and after I input 2 numbers it shows: 我很确定这是正确的语法,但是当我运行它时,它显示一个空白屏幕,并且在输入2个数字后显示:

64 64

120 120

Enter height in inches: 输入以英寸为单位的高度:

Enter weight in pounds: 以磅为单位输入重量:

You are 64 inches tall and weigh 120 pounds. 您身高64英寸,体重120磅。

According to some tutorials, it's supposed to display "Enter height in inches:" before I input the 1st number and "Enter weight in pounds:" before I input the 2nd number. 根据一些教程,应该在输入第一个数字之前显示“以英寸为单位输入身高:”,在输入第二个数字之前显示“以磅为单位输入体重”。 Please help me! 请帮我!

I'm using Eclipse to write my programs and MinGW as the compiler if that's relevant. 如果相关,我正在使用Eclipse编写我的程序,并使用MinGW作为编译器。

尝试使用scanf_s而不是scanf,我只运行了它就可以了。

Its a bug in eclipse and this has been reported by most of the people using eclipse and MinGW. 它是eclipse中的一个错误,大多数使用eclipse和MinGW的人都报告过。

To overcome this problem, you could use fflush(stdout) after every call to printf or use the following in the start of main : 为了克服这个问题,您可以在每次调用printf之后使用fflush(stdout)或在main的开头使用以下内容:

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

This will cause stdout and stderr to flush immediately whenever it is written to. 每当写入stdoutstderr时,它将立即刷新。

I suggest usying Putty if on Windows or command line on Mac OSX. 我建议您在Windows或Mac OSX上使用Putty。 Use "Wal Werror" compiler 使用“ Wal Werror”编译器

Yes, you need to wait for it to display the output before enterning number. 是的,您需要先等待它显示输出,然后再输入数字。

Eg you run the program When this line appears 例如,您运行程序当此行出现时

Enter height in inches:

then enter 然后输入

 64

then when this appears 然后当出现

Enter weight in pounds:

Then enter 然后输入

 120

then output should be as expected 然后输出应如预期

I would suggest you to user sscanf insted of scanf and add fgets to the top would be more logic. 我建议您对sscanf用户使用scanf并在顶部添加fget会更具逻辑性。

It would be: 这将是:

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*/

and same of the other one 和另一个

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

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