我正在尝试在C中为应用程序创建命令行.
int main(int argc, char const *argv[])
{
char cmd[40];
do {
scanf("%[^\n]", cmd);
if(strcmp(cmd, "start"))
new_game();
} while(strcmp(cmd, "exit"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不能使用"%s",因为命令可能有多个参数,所以我需要使用异常并忽略新行char.问题是程序在插入一次后不再调用scanf.为什么会这样?
谢谢
fgets相反,请使用以读取整个输入,如下所示:
char cmd[255];
fgets(cmd, 255, stdin);
Run Code Online (Sandbox Code Playgroud)
样本可以在这里找到.
此外,strcmp在您的示例中未正确使用该函数.Strcmp收益:
所以在你的例子中,你应该使用strcmp(str1, str2) == 0或!strcmp(str1, str2)简称.
注意: 使用时应小心fgets.换行符被认为是有效的fgets,它包含在字符串中.另一方面,scanf(" %s")换行符不包含在结果字符串中.