我正在编写一个基本的C程序,可以将摄氏度或华氏度相互转换。
我有一个
代码如下:
我有一个
scanf
语句,用户在其中输入要转换的温度,然后是一个printf
语句,询问该温度是否为摄氏度还是华氏度。当我编译时,要求输入字符c或f的scanf
会捕获前一个scanf
的\n
。这是根据我的调试器显示的。代码如下:
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;
}
我有点不明白,我知道scanf
在这种情况下会在输入流中查找下一个字符,但为什么此时仍然存在\n
在输入流中呢?除了get char之外,还有其他“正确”的方法来解决这个问题吗?