Search code examples
cswitch-statementstrtok

Tokenizing a string inside a switch statement - C


I've been having a lot of trouble using strtok in a switch statement . Here's the code

int main(int argc, char *argv[]) {

  char phrase[256];
  printf("type a phrase to examine\n\n");
  fgets(phrase, 256, stdin);

  printf("phrase: %s\n", phrase);

  int opt;

  while ((opt = getopt(argc, argv, "l")) != -1) {
     switch (opt) {
     case 'l':
         //prints all words as a list
         char *token = strtok(phrase, " ");

         while (token != NULL) {
             printf("%s\n", token);
             token = strtok(NULL, " ");
             break;
         }
     }
 }
 return 0;
}

When it prints, it only shows me the first word but nothing else after the spaces

i've also tried using strtok when it's not in the switch statement but it works fine. I'm not sure what I'm doing wrong.


Solution

  • the break; statement should be out of the while loop. You should have realized yourself had you indented properly the source (I edited your question, to make it more apparent, although).

    After the first pass through the loop, you get the break; and you get out of the loop, instead of getting out of the switch statement.

         case 'l':
             //prints all words as a list
             char *token = strtok(phrase, " ");
    
             while (token != NULL) {
                 printf("%s\n", token);
                 token = strtok(NULL, " ");
             }
             break;  /* now the break gets out of the switch */
    

    will do a better job.

    There's a more readable way, IMHO, that will allow you to use a for loop:

             //prints all words as a list
             for (char *token = strtok(phrase, " ");
                  token != NULL;
                  token = strtok(NULL, " "))
             {
                 printf("%s\n", token);
             }