首页 > 解决方案 > 在 while 条件下使用 strcmp 来中断循环

问题描述

我需要编写一个程序,该程序需要循环并从用户那里获取输入。为了打破循环,用户需要在键盘上键入 exit。以下是我的代码:

int main()
{
    char input[100];
    char terminate[100]="$exit";
    //if input does not equals to terminate keep asking user for input
    while(strcmp(input, terminate)!=0)
    {
        printf("$");
        fgets(input,100,stdin);
    }//otherwise, exit the program
}

我尝试测试上面的代码,但即使在输入单词 exit 后它也会继续循环。非常感谢您的帮助。:)

标签: c

解决方案


fgets将读取将包含在最终字符串中的 EOL 字符。

您可以strncmp只使用 "terminate": 中的字符strncmp(input, terminate, strlen(terminate)


推荐阅读