简体   繁体   English

C-如何多次使用带有scanf的字符串

[英]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. 为了更好地封装这种行为,定义某种比较字符串并返回枚举元素的函数是一种很常见的做法,但在本问题中并非必需。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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