简体   繁体   中英

C - How to use a string with scanf multiple times

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
     char terminal[100];

     printf("Enter cmds: ");
     scanf(" %s", terminal);

     if(strcmp(terminal, "help") == 0){
           printf("test");
           scanf(" %s", terminal); // trying to detect if a user types
                                   // "help" the menu will pop up again
     }

     return 0;
     }

When a user types "help", the menu pops up, (good so far). But when they type "help" again, the menu does not pop up. Does anybody know what is going on?

The initial comments hit the nail on the head here. You need to loop over new input multiple times. This can be done fairly easily.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char terminal[100];

    printf("Enter cmds: ");

    // this expression will return zero on invalid input, exiting the loop
    while (scanf("%99s", terminal) == 1) {  
        // your if statement and other code you want to repeat go here.
    }
}

To better encapsulate this kind of behaviour, defining some sort of function that compares strings and returns an element of an enum is a very common practice, but not required in this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM