4

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Lost Odinson
  • 418
  • 1
  • 5
  • 14

2 Answers2

4

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'){
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • super helpful, and it worked beautifully. I chose the other answer because it seemed more adaptable. Thanks for your help – Lost Odinson May 06 '14 at 05:38
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.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33