scanf在此c程序中无法正常工作

时间:2016-04-28 05:09:16

标签: c

我写了一个小代码来从华氏温度到摄氏温度。我想继续输入数据,直到我按下除“y”之外的任何其他键。但是这个循环不能以这种方式工作并在一次迭代后停止。

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
    printf("again\n");
    scanf("%d",&far);
    //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
    cen = (5*(far-32))/9;//or this way we can use this formula
    printf("\n%d\t%d",far, cen);
    printf("ch=%c",ch);
    scanf("%c",&ch);
    }while(ch == 'y');

return 0;
}

这是什么问题? P.S 我添加了一行并制作了一个像这样的新代码

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
    printf("again\n");
    scanf("%d",&far);//here we press carriage return. this value is in stdin
    //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
    cen = (5*(far-32))/9;//or this way we can use this formula
    printf("\n%d\t%d",far, cen);
    scanf("%c",&ch);//putting a space before %c makes the newline to be consumed and now it will work well
    if((ch == '\r')|| (ch == '\n'))
        printf("1\n");
    printf("ch=%c",ch);//this takes the carriage return in stdin buffer
    }while(ch == 'y');

return 0;
}

我需要知道这里的回车是\ r \ n或\ n?

5 个答案:

答案 0 :(得分:3)

输入scanf("%d",&far);的值并按Enter键时,scanf将回车符存储在缓冲区中。当它遇到代码scanf("%c",&ch);中的第二个scanf时,它会将缓冲区中的回车符作为&#39; ch的输入。所以它不会等待用户输入。

请查看帖子here

如其中一个回复中所示,解决方案是在scanf中放置一个空格

scanf(" %c",&ch);

答案 1 :(得分:2)

您应该始终检查scanf的返回值。如果用户未输入有效整数,则首次使用scanf可能会失败,在这种情况下,您使用far而未初始化它(这是未定义的行为)。 scanf返回已成功扫描的项目数。如果您要求scanf扫描一个整数,那么如果它成功地设法扫描整数,它应该返回1.

int scanresult = scanf("%d", &far);
if (scanresult != 1)
{
    puts("Invalid input or unexpected end of input");
    return 1;
}

此外,%c转换说明符的唯一性在于,与其他转换说明符不同,它不会导致scanf吞噬任何前面的空格。要强制scanf吞噬空格(例如换行符,回车符,空格,制表符等),只需在%c之前添加一个空格字符,例如

scanresult = scanf(" %c", &ch);

对于scanf,空格字符实际上是一个解析和跳过所有空格的指令。

答案 2 :(得分:0)

这是因为缓冲区中剩余的旧行字符。您只需将scanf替换为此行:

while((ch = getchar()) == '\n');

在许多情况下,您需要与ungetc()结合使用相同的技术。

答案 3 :(得分:0)

添加fflush()函数,就在scanf(“%c”,&amp; ch)之上。因为CONSOLE INPUT的缓冲区存储未返回程序的字符。在之前的scanf中按下了哪个ENTER:

#include <stdio.h>

int main() {
   char ch='y';
   int far, cen;
do {
   printf("again\n");
   scanf("%d",&far);
   //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero     so we can make 5/9 to 5.0 / 9.0
   cen = (5*(far-32))/9;//or this way we can use this formula
   printf("\n%d\t%d",far, cen);
    printf("ch=%c",ch);

   scanf("%c",&ch);    // This scanf will be ignored, because loads last
                       // character from buffer that can be recognized 
                       // by scanf which is pressed "ENTER" from previous scanf 
   printf("%d", ch)     // Shows 10, which is ASCII code of newline
   fflush(stdin);       // Clear buffer
   scanf("%c",&ch);     // Now it will prompt you to type your character.

   // printf("%c"ch); //Without fflush, it must show 10, which is \n code    
   }while(ch == 'y');

    return 0;
   }

答案 4 :(得分:-2)

如果在Y之后按“空格”或“返回”,则这是您在%C中找到的字符