c - 当用户在C中输入“退出”时如何让程序终止
问题描述
当我输入“退出”时,程序似乎并没有从我下面的代码中终止;当用户键入“退出”时,是否有我遗漏的东西或者有更好的方法来终止程序?
在我的代码中,您还可以看到它在 EOF 发生时终止,这可以正常工作,只是在我输入“exit”时它不会终止。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main () {
char input[512];
char * charp;
int len = 0;
printf("> ");
if(fgets(input, 512, stdin) == 0 || input == "exit") { /* reads in input from user no more than 512 chars including null terminator*/
printf("exitting program");
exit(0);
}
printf("You entered: %s", input);
len = strlen(input);
charp = strtok(input, " ' '\t"); /* splits the string on delimiters space '' and tab*/
while (charp != NULL) {
printf("%s\n", charp);
charp = strtok(NULL, " ' '\t");
}
printf("The len of input = %d ", len);
return(0);
}
解决方案
输入==“退出”
是错的。应该是strcmp(input,"exit")==0
,否则你将输入字符串的地址与内存中字符串“exit”的地址进行比较,而不是内容。
确保先从通话中删除换行符fgets
,或使用strncmp(input, "exit", 4)
推荐阅读
- python - NoSuchElementException:无法在 MultiLayerPerceptronClassifier 中找到图层的默认值
- php - 使用 VUE 对频道 laravel 回声没有回调
- asp.net-core - 结合 Razor Pages 和 ApiControllers 的应用程序中的 Asp.net 核心异常处理
- javascript - 如何在lodash中使用orderBy对具有行跨度的表行进行排序?
- multithreading - 使用多线程在单个事务中进行多次插入
- python - 将 RGB 颜色应用于 HSV 单色图像
- pandas - 如何将 1 列数据框转换为多列?
- python - 带有 Gspread 的 Django Python:“选择”必须是包含(实际值,人类可读名称)元组的可迭代
- android - 致命信号 11 (SIGSEGV),代码 1 (SEGV_MAPERR),tid 22274 (hwuiTask1) 中的故障地址 0x0
- php - PHP 检查 curl 结果是 XML 还是 HTML