Question

I'm writing a basic C program that will convert either Celsius or Fahrenheit to the other.

I have a scanf statement where the user enters the temperature they want to convert, and then a printf statement asking for whether that temperature was in c or f. when I compile, the scanf asking for char c or f is instead grabbing the \n from the previous scanf. according to my debugger.

the code looks like this:

int celcius(void){
double originalTemp = 0;
double newTemp;
char format;

printf ("enter a temperature: ");
scanf ("%lf",&originalTemp);    //what is the original temp?

printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f

scanf("%c", &format);       //why do I need to do this twice??, this one grabs \n
scanf("%c", &format);       //this one will pick up c or f


if (format == 'c'){
    newTemp = originalTemp*1.8+32;
    printf("%.2lf degrees Farenheit\n", newTemp);
} //convert the Celcius to Ferenheit


else if (format == 'f'){
    newTemp = (originalTemp-32)/1.8;
    printf("%.2lf degrees Celcius\n", newTemp);
} //convert the Ferenheit to Celcuis

else {
    printf ("ERROR try again.\n");
} //error if it isn't f or c

return 0;
}

am I missing something? I know thatscanf looks in the input stream for the next char in this case, but why is \n still in the input stream at this point? and is there a "proper" way to fix this other than get char?

Was it helpful?

Solution 2

The rule is to write a getchar() after every integer/float/double input if you take char/string inputs later. This getchar() flushes out the \n from the input buffer which is leftover by taking the integer/float/double input.

So just write a getchar(); after scanf ("%lf",&originalTemp); and you'll be fine.

OTHER TIPS

Space in the format string matches whitespace, so you can just match away/skip the cr/lf;

printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f

scanf(" %c", &format);   // get next non white space character, note the space

if (format == 'c'){
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top