I'm working through O'Reilly's Practical C Programming, just for fun, and one of the exercises in section 5 is to write a program to convert °C to °F and vice versa. Here's what I have so far..
Now, there are undoubtedly far more elegant ways of doing this, but for the moment, I'm right at the basics. What I can't understand is that the program compiles without any errors, it asks the user to choose which conversion he wants.. and then prints out the Please enter temperature in degrees Celsius : and exits.
char choice ; // which conversion do I want ?
int userChoice ; // the int to pass to the if .. then
char input ; // the number to be converted
float temp ; // the temperature to start with
float result ; // the result
int main ()
printf ("\n(1) - Celsius - Fahrenheit ") ;
printf ("\n(2) - Fahrenheit - Celsius\n\n") ;
fgets (choice, sizeof(choice), stdin) ;
sscanf (choice, "%d", &userChoice) ;
if (userChoice == 1)
printf ("\n\nPlease enter temperature in degrees Celsius : ") ;
fgets (input, sizeof(input), stdin) ;
sscanf (input, "%f", &temp) ;
return 0 ;
Why? I don't get it. The fgets is the same format as the previous time when input was asked for, and yet bang - it exits.