在while循环中扫描字符

时间:2014-02-25 21:33:41

标签: c while-loop char scanf

char player_select(void){

    char player = 'n';

    while(player == 'n'){
        printf("Select your player (X or O): ");
        scanf("%c\n", &player);

        if(player != 'X' && player != 'O'){
            printf("Invalid input. Try again.\n");
            player = 'n';
        }
    }

printf("Your character input is: %c\n", player);
exit(0);
return player;
}

我在这里得到了一些奇怪的输出:

选择您的播放器(X或O):X

输入无效。再试一次。

选择您的播放器(X或O):i

您的角色输入是:X

3 个答案:

答案 0 :(得分:3)

scanf()

的使用不正确
// scanf("%c\n", &player);
scanf(" %c", &player);

'\n'中的"%c\n"并不符合您的想法。 '\n'告诉scanf()使用'\n'' '之类的空格,直到出现非空格。您输入的内容是而不是

由于stdin是缓冲的,因此文本本身通常不会被读取,直到跟随'\n'

详细解释为什么事情失败变得复杂。简而言之,请使用" %c"代替"%c\n"。或者更好的是,使用fgets()

buffer player[10];
fgets(ch, sizeof ch, stdin);
if(player[0] != 'X' && player[0] != 'O') { ...

答案 1 :(得分:1)

我希望这对你有用。 我已移除\n内的scanf,我已添加while(getchar()!='\n');以清空stdin

char player_select(void){

char player = 'n';

while(player == 'n'){
    printf("Select your player (X or O): ");
    scanf("%c", &player);

    if(player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }
    while(getchar()!='\n');
}

这是输出:

Select your player (X or O): A
Invalid input. Try again.
Select your player (X or O): X
Your character input is: X

答案 2 :(得分:0)

尝试:

    if (scanf("%c\n", &player) == 1 && player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }

scanf带入if,从上面的代码中移除,并检查其返回值== 1

如果这还不够,您可以尝试从scanf掩码中删除\n