为什么scanf会抓取\n?

4
我正在编写一个基本的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之外,还有其他“正确”的方法来解决这个问题吗?

2个回答

4

在格式字符串中的空格表示匹配空白字符,所以你可以直接匹配/跳过换行符;

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'){

非常有帮助,而且运行得很好。我选择了另一个答案,因为它似乎更具适应性。感谢您的帮助。 - Lost Odinson

2
规则是在每个整数/浮点数/双精度浮点数输入后写一个 getchar(),如果您之后需要输入字符/字符串。这个getchar()会清除输入缓冲区中由于输入整数/浮点数/双精度浮点数留下的 \n
所以只需在 scanf ("%lf",&originalTemp);后写一个 getchar();,一切都会好起来。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接