[英]C - How to use a string with scanf multiple times
这是我的代码:
#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;
}
当用户键入“帮助”时,菜单弹出(到目前为止很好)。 但是,当他们再次键入“帮助”时,菜单不会弹出。 有人知道发生了什么吗?
最初的评论在这里引起了人们的关注。 您需要循环新的输入多次。 这可以很容易地完成。
#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.
}
}
为了更好地封装这种行为,定义某种比较字符串并返回枚举元素的函数是一种很常见的做法,但在本问题中并非必需。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.