https://www.codechef.com/submit/FLOW010

Can someone please tell me why this code is not working for Id and Ship problem??

#include <stdio.h>

int main(void) {

int t;
char x;
scanf(“%d”,&t);
while(t–)
{
scanf(“%c”,&x);
if(x==‘B’||x==‘b’)
printf(“BattleShip\n”);
else if(x==‘C’||x==‘c’)
printf(“Cruiser\n”);
else if(x==‘D’||x==‘d’)
printf(“Destroyer \n”);
else if(x==‘F’||x==‘f’)
printf(“Frigate\n”);
}

return 0;

}

After scanning a char (B or C or D or any char) for next iteration you need to escape the next char (probably a newline or any such char which is not needed).
Workaround :- scanf(" %C"); // note the space before %

And also please make sure from next time when you attach a link, check if its your submitted solution link. The link that you attach is of IDE link with no code of yours.

1 Like

Thanks brother it worked but i am still not able to understand how? Can you please elaborate more??

Adding space before % comes under “formatting input string part”, which does nothing but omits newline char (’\n’) or any white space char, and accepts next char. Read more about scanf and format specifiers you will get to know more.

2 Likes