#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
I understood the use of " %c" rather than “%c”, but why can’t we use fflush(stdin) instead?
It also clears the buffer and removes any whitespaces.
I wrote fflush(stdin) and it said “Wrong Answer”.
Here is the code : -
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int n;
scanf("%d",&n);
char c;
while(n--)
{
scanf("%c",&c);
fflush(stdin);
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");
}
}
return 0;
}
fflush(stdin)
is erroneous.