c - 为什么输入某些内容并按回车后scanf不会停止
问题描述
代码只是继续接受输入,并没有继续 if 逻辑,我不知道为什么
while (1){
// get command
char cmd[6];
scanf("%s", cmd);
if (cmd == "exit"){
return 0;
} else if(cmd == "task\n"){
taskHandler();
} else if(cmd == "event"){
eventHandler();
} else if(cmd == "show"){
showItems();
}
}
解决方案
在 C 中,您不能使用==
比较字符串,因为它会比较指针的值,即内存中具有字符串数据的位置。如果要比较实际数据,则必须使用strcmp
,即:
if(cmd == "exit") {
...
}
应该
if(strcmp(cmd, "exit") == 0) {
...
}
int strcmp(const char* str0, const char* str1)
返回是否str1
按字典顺序小于、等于或大于(-1
分别为0
、 和1
),所以如果它返回0
,则str0
和str1
相等。
我也会使用break
代替 thereturn 0
并将 the移到循环return 0
之外。while(1)
推荐阅读
- c - C指针中的奇怪行为
- java - Java BigDecimal long 带十进制转换
- javascript - ClassName.variable 总是静态成员变量吗?
- flutter - Flutter:如何在 GetX 上监听变量变化
- database - FutureBuilder 和 ListView.builder
- html - Bootstrap Grid - 在 div 中获取文本和图像之间所需的间距/填充的问题
- flatpickr - Livewire 和 Flatpickr - 重新渲染后失败
- python - 我正在尝试创建一个在没有 CSV 模块的情况下读取 CSV 文件的函数,但遇到格式错误
- vue.js - 如何在 vuex 动作中制作循环,axios 循环
- google-cloud-dataflow - Apache Beam 中的窗口化和水印:Google 数据流