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.
the
break;statement should be out of thewhileloop. 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 theswitchstatement.will do a better job.
There's a more readable way, IMHO, that will allow you to use a
forloop: