scanf和printf在第一次跳过后才跳过

时间:2013-02-27 17:15:23

标签: c

这里有什么问题? scanf似乎没有在while循环中工作。我试图找出元音和直到用户想要的为止。

以下是代码:

#include <stdio.h>
main()
{
    char x,c;
    do
    {
        printf("enter\n");
        scanf("%c",&x);
        if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
            printf("vowel\n");
        else
            printf("consonent\n");

        printf("do u want to continue ?(y/n)\n");
        scanf("%d",&c);
        if(c=='n')
            printf("thnks\n");

    } while(c=='y');
    return 0;
}

6 个答案:

答案 0 :(得分:6)

您正在尝试使用%d读取字符,这是错误的。请改用%c

答案 1 :(得分:2)

将代码更改为scanf("%c",&c)原始代码将y / n条目作为数字而不是字符

编辑:

可能您正在使用getcfgets而不是使用{{1}}或{{1}}来获取第一个字符。

答案 2 :(得分:1)

我认为问题可能在这里:         的scanf( “%d”,和C); 它应该是:

    scanf("%c",&c);

答案 3 :(得分:1)

这是正确的代码:

#include <stdio.h>

int main()
{
    char x,c;
    do
    {
        printf("enter\n");
        scanf("%c",&x);
        getchar(); //to remove the \n from the buffer
        if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
            printf("vowel\n");
        else
            printf("consonent\n");
        printf("do u want to continue ?(y/n)\n");
        scanf("%c",&c); //Here you were using %d instead of %c
        getchar(); //to remove the \n from the buffer

        if(c=='n')
            printf("thnks\n");
    }while(c=='y');

    return 0;
}

答案 4 :(得分:0)

两个scanfs应该像这样改变:

scanf(" %c",&x);

...

scanf(" %c",&c);

请注意%之前的空格,这很重要:它会消耗前导空格,其中包括处理输入后stdin中留下的结束字符。

答案 5 :(得分:-1)

请尝试使用此代码多次运行循环。

编辑:没有fflush(stdin)的不同解决方案。请将一个包含8个字符的字符串定义为

char str[8];

并将循环中的代码修改为

fgets(str, 8, stdin); // To read the newline character
printf("do u want to continue ?(y/n)\n");

scanf("%c",&c);
fgets(str, 8, stdin); // To read the newline character
相关问题