C语言接收指定范围整数时输入字母重复报错问题求解
问题修复说明
根本原因
- 未判断
scanf的返回值:当输入非整数内容时,%d匹配失败,scanf不会修改rangenum、newline变量,也不会消费缓冲区的错误字符,错误内容会被下一轮循环重复读取形成死循环。 rangenum未初始化,首次匹配失败时取值为内存随机值,大概率不在指定范围内,会优先触发范围错误分支,永远走不到类型错误逻辑。- 范围错误分支未处理缓冲区残留数据,进一步加剧死循环问题。
修复思路
- 优先校验
scanf返回值,返回值不等于2(未成功匹配整数+换行)时直接判定为类型错误,清空缓冲区后报错。 - 初始化
rangenum变量,避免未定义行为。 - 调整判断顺序:先校验输入格式合法性,再校验数值范围合法性,所有错误分支统一处理缓冲区残留。
- 增加尾随字符校验:如果整数后有多余非换行字符,同样判定为非法输入。
修正后完整代码
#include <stdio.h> void clearStandardInputBuffer(void) { while (getchar() != '\n') { ; } } int getIntFromRange(int lowbound, int upperbound) { int rangenum = 0; char newline = 'x'; while (1) { int scanf_ret = scanf(" %d%c", &rangenum, &newline); // 匹配失败:输入不是合法整数 if (scanf_ret != 2) { clearStandardInputBuffer(); printf("ERROR: Value must be an integer: "); continue; } // 整数后有多余非法字符 if (newline != '\n') { clearStandardInputBuffer(); printf("ERROR: Value must be an integer: "); continue; } // 校验数值范围 if (rangenum >= lowbound && rangenum <= upperbound) { return rangenum; } else { printf("ERROR: Value must be between %d and %d inclusive: ", lowbound, upperbound); } } return 0; } int main(void) { getIntFromRange(0, 1); return 0; }
内容的提问来源于stack exchange,提问作者FishLord
相关产品推荐
相关产品推荐

