Home > other >  loop is running 5 times but asking for input only 2 times
loop is running 5 times but asking for input only 2 times

Time:11-21

This is my code, here I am taking char input each time loop runs.

I am giving 5 inputs but it is only responding to only 2 of them.

#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

CodePudding user response:

The problem is your "scanf"-function in the loop. The char %c identifier reads \n as input if you use: scanf("%c", &c) If you write it as follows: scanf(" %c", &c) your problem is solved.

CodePudding user response:

The problem is that scanf("%c", &c) only reads one character, but the input has space between letters and space is also an ascii character. The spaces are causing the problem, not the newline(\n) after 5. you can use scanf(" %c", &c), with a space before %c, this way scanf ignores white-space characters like space and newline, no matter how many they are. this solution works even if you put many spaces between your inputs.

CodePudding user response:

there is no problem in your code Try any other compiler. Sometimes this type of issue resolve after changing the compiler

  • Related