0

This code should print the word starting with input character but something wrong with it.

I have already checked by using fflush(stdin)

#include<stdio.h>
int main(){
    char str;
    int n,in;
    scanf("%d",&n);
    for(in=0;in<n;in++){  
        scanf("%c",&str);
        for(in=0;in<n;in++){
            if((str=='b')||(str=='B'))
                printf("Battleship");
            else if((str=='c')||(str=='C'))
                printf("Cruiser");
            else if((str=='d')||(str=='D'))
                printf("Destroyer");
            else
                printf("Fringate"); 
        }
   }
}

When I am providing test case, it is not taking input and getting out of the program.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sam
  • 1
  • 1
  • Give the white space before `%c` to consume the newline character from the input, `scanf(" %c",&str);` And you intended to put `scanf()` inside loop ? else `str` will always same for `n` iteration – Achal Apr 14 '19 at 04:10
  • the second loop is not running and it is automatically printing the prevous output – sam Apr 14 '19 at 04:12
  • why is that so since i have provided scanf it should scan inside the loop before printing the output – sam Apr 14 '19 at 04:15
  • ok i got the solution thank you – sam Apr 14 '19 at 04:17
  • My bad, I didn;t see that. – Achal Apr 14 '19 at 04:17
  • Use differenet variable in second loop, instead of 'in', use some other name – Sabith Apr 14 '19 at 04:17
  • why should i give whitespace,please give me the reason for that ,i didnt get the logic to do that – sam Apr 14 '19 at 04:20
  • 1
    You need `" %c"` because [`scanf()` leaves the newline in the input buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). You should be cautious about [Using `fflush(stdin)`](https://stackoverflow.com/questions/2979209/using-fflushstdin); it doesn't work everywhere. You should be testing the return value of `scanf()` every time you call it so you can spot EOF and other problems reliably. – Jonathan Leffler Apr 14 '19 at 04:56
  • Also, in English the ship type is "frigate" not "fringate". And don't you have some squares that have no vessel in them? At the moment, you have frigates everywhere you don't have a bigger vessel. – Jonathan Leffler Apr 14 '19 at 04:58

0 Answers0