C语言如何检测用户输入的字符串中是否包含指定字符'!'
C语言密码检测工具问题修复
错误原因
- 核心错误:
strchr函数参数类型不匹配。strchr第二个参数要求传入单引号包裹的字符常量,你代码中传入了双引号包裹的字符串"!",双引号包裹的内容本质是字符串首地址,类型完全不符合函数要求,导致判断永远不成立,special变量始终为0。 - 其他附加错误:
- 调用
exit()函数却没有引入<stdlib.h>头文件,会触发编译错误 scanf_s传入数组参数时不需要加取地址符&,数组名本身就代表首地址,加&会导致类型不匹配void main是非标准的main函数写法,兼容性差,标准写法为int main(),函数末尾需要返回状态码exit()调用需要传入退出状态码,无参数调用不符合函数定义要求
- 调用
修复后完整代码
#include <stdio.h> #include <string.h> #include <stdlib.h> // 引入exit函数对应的头文件 int main() { // check for special characters // check for length of password char password[30]; int length; int len = 15; printf("Dear user please enter a password:\n "); // 去掉password前的& scanf_s("%s", password, 30); length = strlen(password); if (length < len) { printf("invalid password (password must be 15 - 30 characters)"); exit(1); // 传入退出状态码 } int special = 0; // 第二个参数改为单引号包裹的字符'!' if (strchr(password, '!') != NULL) { special = 1; } printf("%d", special); return 0; }
内容的提问来源于stack exchange,提问作者Punz
相关产品推荐
相关产品推荐

