循环是 运行 5 次,但只要求输入 2 次

loop is running 5 times but asking for input only 2 times

这是我的代码,每次循环运行时我都会输入 char

我提供了 5 个输入,但它只响应了其中的 2 个。

#include <stdio.h>

int main()
{
    int t;
    scanf("%d",&t);
    while (t--)
    {
        char c;
        scanf("%c",&c);
        if(c =='b' || c== 'B')
            printf("BattleShip\n");
        else if(c=='c' || c=='C')
            printf("Cruiser\n");
        else if(c == 'd' || c=='D')
            printf("Destroyer\n");
        else if(c=='f' || c=='F')
            printf("Frigate\n");
    }
}
Input:
5 
b f c b f

Output:
BattleShip
Frigate

你的代码没有问题 尝试任何其他编译器。 有时此类问题会在更改编译器后解决

问题出在循环中的“scanf”函数。如果您使用: char %c 标识符读取 \n 作为输入: scanf("%c", &c) 如果你这样写: scanf(" %c", &c) 你的问题解决了。

问题是scanf("%c", &c)只读取了一个字符,但是输入的字母之间有space而且space也是一个ascii字符。 space 导致了问题,而不是 5 之后的换行符 (\n)。 您可以使用 scanf(" %c", &c),在 %c 之前使用 space,这样 scanf 忽略 white-space 字符,如 space 和换行符,无论如何 他们很多。这个解决方案即使你放很多 spaces 在您的输入之间。