C++标识符校验程序checkIdentifier仅返回false问题排查求助
问题根因
你的代码无论输入什么都返回false的核心原因是checkKeyword函数存在未定义行为:
- 该函数声明返回
bool类型,但仅在输入匹配到C++关键字的分支写了return true,遍历完全部32个关键字都不匹配的场景下,没有写return false的返回语句。 - C++标准规定非void类型函数如果没有显式返回值,返回结果是不确定的垃圾值,绝大多数场景下这个垃圾值会被判定为
true,导致checkIdentifier的判断条件中checkKeyword()==true永远成立,直接返回false。
其他需要修正的问题
- 头文件引用错误:你引入了POSIX专用的
<strings.h>,如果要使用strstr函数,标准C++应该引用<cstring> - 关键字拼写错误:C++关键字
volatile被你错写为voltile,会导致该关键字无法被正确识别 - 标识符校验规则不全:当前仅判断了是否包含
#、首字符是否为数字,既没有覆盖!@$%等其他非法字符,也没有允许首字符为下划线的合法场景,不符合C++标识符的标准规则。
修复后代码
#include<bits/stdc++.h> #include<cstring> #include<cctype> using namespace std; string ishfakur; void getInput(){ cin>>ishfakur; } bool checkKeyword(){ string keyword[32]={ "auto","double","int","struct","break","else","long", "switch","case","enum","register","typedef","char", "extern","return","union","const","float","short", "unsigned","continue","for","signed","void","default", "goto","sizeof","volatile","do","if","static","while" } ; for(int i=0;i<32;i++){ if(ishfakur==keyword[i]){ return true; } } // 新增非关键字的返回语句 return false; } bool checkIdentifier(){ // 校验长度、首字符合法性 if(ishfakur.length()>=30 || !(isalpha(ishfakur[0]) || ishfakur[0] == '_')){ return false; } // 校验后续字符合法性 for(int i=1;i<ishfakur.length();i++){ if(!(isalnum(ishfakur[i]) || ishfakur[i] == '_')){ return false; } } // 校验是否为关键字 if(checkKeyword()){ return false; } return true; } void giveOutput(bool st){ if(st){ printf("valid"); }else{ printf("invalid"); } } int main(){ bool status; getInput(); status = checkIdentifier(); giveOutput(status); return 0; }
内容的提问来源于stack exchange,提问作者Mohammad Ishfakur
相关产品推荐
相关产品推荐

