c - 在 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 后它也会继续循环。非常感谢您的帮助。:)
解决方案
fgets
将读取将包含在最终字符串中的 EOL 字符。
您可以strncmp
只使用 "terminate": 中的字符strncmp(input, terminate, strlen(terminate)
。
推荐阅读
- maven - 在maven项目中使用AspectJ:编织不起作用
- r - 有什么方法可以删除 Emoji 并在 R 中保留其他特殊字符?
- python - 为什么 BeautifulSoup 的 unwrap 方法会删除标签内的文本而不是删除标签?
- javascript - 将 JSON 对象转换为 protobuf IStruct
- html - min-width 有效,但 min-height 无效
- python - 将 JSON 转换为 Python 中的列表列表
- ansible - Ansible 条件查找
- swift - 如何使用在 Swift 中返回 MultiArray(Double) 的模型进行预测
- android-fragments - 如何通过putExtra getExtra在一个webView中显示多个链接
- r - 多项式模型的 R 中的 Wald/LRT/Score 假设检验