简体   繁体   中英

Trouble with input using scanf()

I'm new to C so I'm having a bit of trouble with 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:

64

120

Enter height in inches:

Enter weight in pounds:

You are 64 inches tall and weigh 120 pounds.

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.

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

Its a bug in eclipse and this has been reported by most of the people using eclipse and MinGW.

To overcome this problem, you could use fflush(stdout) after every call to printf or use the following in the start of 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.

I suggest usying Putty if on Windows or command line on Mac OSX. Use "Wal Werror" compiler

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.

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

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