0

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.

1
  • 1
    Your symptoms don't correspond to your code Commented Sep 25, 2014 at 3:30

4 Answers 4

2

Its a bug in eclipse and this has been reported by many people using eclipse and MinGW.

To fix this you could do one of the following:

  • Add the following code at the start of the main function:

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

    This will cause stdout and stderr to flush immediately whenever it is written to.

  • Use fflush(stdout) after every call to printf.

Sign up to request clarification or add additional context in comments.

Comments

2

Try using scanf_s instead of scanf , i just ran it and it worked.

Comments

0

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

Comments

0

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.

E.g. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.