0

I am making a morse code where when we enter a word or number or sentence etc, it gets turned into morse but I can't exit my do while loop.

 printf("Enter anything you want to be translated to morse, if you want to listen to what exit sounds like and exit the program, type 'Exit'\n");
    do {
        fgets(Morse, sizeof Morse, stdin);


        for (int z = 0, length = strlen(Morse); z < length; z++) {
            int n = 0;
            n++;
        }
        for (int i = 0, length = strlen(Morse); i < length; i++)


            switch (Morse[i]) {

up line ends where my switch cases come in, in which I check which character it is and at the end of my do while loop, it ends like :

}

    }while(strcmp(Morse, "Exit") != 0);
    return 0;

but even when I type exit, it doesn't exit. What should I do?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Alternatively you can use `strncmp( Morse, "Exit", 4 )` which will check the first 4 characters, that can be useful if you for some reason decide to switch to e.g. `scanf` which will not add the newline character to the end. – aulven May 08 '20 at 23:24
  • The best thing to do is `char str[8]; if (sscanf(Morse, "%7s", str) == 1 && strcmp(str, "Exit") == 0) break;` That will handle leading and trailing whitespace, including the newline that `fgets` may put in the buffer. And the loop should be `while (fgets(Morse, sizeof Morse, stdin) != NULL)` – user3386109 May 08 '20 at 23:30
  • Since you tagged as C++, you should use `std::string` and `std::getline`. The `std::string` can expand dynamically. The C language only supports character arrays and character arrays can overflow. If you want some Undefined Behavior, remove the terminating `'\0'` from your character array. The operation will go past the array, accessing memory until it finds the terminating character (or the OS yells at you). – Thomas Matthews May 09 '20 at 00:04

0 Answers0