Why does scanf capture \ n?

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);    //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 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?

+4
2

, getchar() integer/float/double, char/string. getchar() \n , , // .

, getchar(); scanf ("%lf",&originalTemp);, .

+2

, / 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'){
+4

Source: https://habr.com/ru/post/1539378/


All Articles