在If Else语句中使用strcmp函数遇到的异常问题求助
输入过长错误内容后strcmp无法识别正确输入的问题解决
你的代码存在几个关键问题,导致了输入异常:
result字符串缺少终止符toLower函数只完成了字符转小写的工作,但没有在result末尾添加C字符串必需的'\0'终止符。当输入过长字符串时,result数组被填满,后续输入短字符串时,result里会残留之前的字符,比如输入"area"后,result实际是"area"加之前残留的字符,变成了更长的非法字符串,strcmp自然匹配不上。修复:在
toLower的循环结束后,给result加上终止符:result[i] = '\0';scanf未限制输入长度,缓冲区溢出function数组大小是13,最多只能存12个字符加终止符,但scanf("%s", function)会读取任意长度的输入,输入超过12字符时会溢出,破坏内存中的其他数据(比如result数组或循环变量),引发不可预测的逻辑错误。修复:限制
scanf的输入长度:scanf("%12s", function);循环条件逻辑错误
你的while条件用了||,意思是只要输入不是其中一个目标字符串就继续循环,这逻辑等价于永远循环(除非触发break)。应该改成&&,表示输入既不是"circumference"也不是"area"时才继续循环:while (!(strcmp(result, "circumference") == 0) && !(strcmp(result, "area") == 0));函数缺少返回值
FunctionChoice声明返回char,但函数内没有return语句,这会导致未定义行为,需要在匹配成功时返回对应的字符。
修复后的完整代码:
#include <stdio.h> #include <ctype.h> #include <string.h> char function[13]; char result[13]; void toLower() { int i; for (i = 0; function[i] != '\0'; i++) { result[i] = tolower(function[i]); } result[i] = '\0'; } char FunctionChoice() { printf("And another one\n"); do { printf("Enter a 4, 5, 13, or 15 character word\n"); scanf("%12s", function); toLower(); if (strcmp(result, "circumference") == 0) { printf("A"); return 'A'; } else if (strcmp(result, "area") == 0) { printf("B"); return 'B'; } printf("Please check your spelling and re-enter\n"); } while (!(strcmp(result, "circumference") == 0) && !(strcmp(result, "area") == 0)); return '\0'; } int main() { printf("There's your print statement\n"); FunctionChoice(); return 0; }
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

