I am writing a basic C program that will convert either Celsius or Fahrenheit to another.
I have an operator scanfin which the user enters the temperature they want to convert, and then an operator printfasking if this temperature was in c or f. when compiling scanfwith a query, char c or f captures \nfrom the previous one instead scanf. according to my debugger.
The code is as follows:
int celcius(void){
double originalTemp = 0;
double newTemp;
char format;
printf ("enter a temperature: ");
scanf ("%lf",&originalTemp);
printf ("enter c if in celcius, enter f if in ferenheit: ");
scanf("%c", &format);
scanf("%c", &format);
if (format == 'c'){
newTemp = originalTemp*1.8+32;
printf("%.2lf degrees Farenheit\n", newTemp);
}
else if (format == 'f'){
newTemp = (originalTemp-32)/1.8;
printf("%.2lf degrees Celcius\n", newTemp);
}
else {
printf ("ERROR try again.\n");
}
return 0;
}
Am I missing something? I know what it scanfwill look like in the input stream for the next char in this case, but why \nremains in the input stream at this point? and is there a “right” way to fix this otherwise than get a char?