C++使用isdigit过滤十二进制转十进制非法字符cin.ignore()故障排查
问题分析
- 错误调用
cin.ignore():该函数的作用是从标准输入缓冲区中读取并丢弃字符,调用时会阻塞程序等待用户输入,你当前处理的是预定义的字符串变量,完全不需要操作标准输入,这是程序运行异常的直接原因。 - 语法错误:
!char.isDigit(duo.at(i))是其他语言的写法,C++没有该语法,且该判断逻辑完全冗余,前面三个分支已经覆盖了所有合法字符,剩余字符直接跳过即可。 - 计算逻辑错误:你将
decValue *= 12放在循环最开始,无论当前字符是否合法都会执行,遇到非法字符时会导致计算结果多乘一次12,即使去掉cin.ignore()也得不到正确的36的结果。 - 无效代码:开头用于跳过空格的while循环计算出的
idx变量没有被后续逻辑使用,属于无效代码。 - 语法不规范:C++标准要求main函数返回值类型为int,你的代码缺少该声明。
- 头文件缺失:
isdigit函数定义在<cctype>头文件中,未引入该头文件会导致部分编译器编译失败。
修复后代码
#include <cctype> #include <iostream> #include <string> using namespace std; int main() { int decValue = 0; string duo = "30-something"; for (char c : duo) { if (isdigit(c)) { decValue = decValue * 12 + (c - '0'); } else if (c == 'x' || c == 'X') { decValue = decValue * 12 + 10; } else if (c == 'e' || c == 'E') { decValue = decValue * 12 + 11; } // 其余字符直接跳过 } cout << decValue << endl; return 0; }
验证说明
输入字符串为30-something时,程序仅读取'3'和'0'参与计算:
- 处理'3':0 * 12 + 3 = 3
- 处理'0':3 * 12 + 0 = 36
- 其余字符全部跳过,最终输出结果为36,符合预期。
内容的提问来源于stack exchange,提问作者codingStudent702
相关产品推荐
相关产品推荐

