Why are we using scanf(" %c",&a) instead of scanf("%c",&a) ? FLOW010

#include<stdio.h>

int main(){
int t;
char a;

scanf("%d",&t);

while(t--)
    {
         scanf(" %c",&a);

           if(a=='b' || a=='B')
        printf("BattleShip\n");

    else if(a=='c' || a=='C')
        printf("Cruiser\n");

    else if(a=='d' || a=='D')
        printf("Destroyer\n");

    else if(a=='f' || a=='F')
        printf("Frigate\n");
}
return 0;

}

1 Like

When doing it the first way, scanf skips the leading whitespace. For instance, consider this input
“2 abcd”
First maybe you read 2 into an int.
Now the istream contains
" abcd"
and " %c" matches
“< a>bcd” (the part inside <>) and from this only the character is extracted, i.e.the whitespace is left. So in the next turn it matches
“< b>cd”, and so on.
Note that this may give wrong inputs if you read multiple space separated strings like “3 ab abcd dds” etc etc. I usually use cin with ios_base::sync_with_stdio(false) and cin.tie(NULL) instead.

2 Likes