C++使用toupper后输入校验循环仍不接受小写字符问题
错误原因
你目前的toupper使用逻辑完全错误:
- 现有代码中
toupper('A')是对常量字符'A'做大写转换,转换结果还是'A'本身,完全没有处理用户输入的custPlanType,因此小写输入不可能通过校验 - 你之前尝试的
toupper(custPlanType == 'A')是先执行custPlanType == 'A'的布尔判断,再对布尔结果做大写转换,逻辑完全不符合需求
修改步骤
- 新增引入
<cctype>头文件,toupper函数定义在该头文件中,缺失头文件属于非标准写法,可能在部分编译器下出现未定义行为 - 在校验前先对用户输入的
custPlanType做大写转换,再和大写的A/B/C/U做比较即可
修改后的完整代码
#include <iostream> // 新增toupper对应的头文件 #include <cctype> using namespace std; int main() { bool custGBTypeValid = false; bool custPlnTypeValid = false; char custPlanType = toupper('Z'); int custUsedData = 1; cout << "Hello, welcome to AT&T wireless. We're here to help you decide if your current plan is what's right for you." << endl; cout << "Here are our plans:" << endl; cout << "Plan A: For $25 per month 0GB are provided. Data is $10 per GB." << endl; cout << "Plan B: For $45 per month 2GB are provided." << endl; cout << "Plan C: For $80 per month 6GB are provided." << endl; cout << "Plan Unlimited: Unlimited data for $100 per month." << endl; while (custPlnTypeValid == false) { cout << "What type of plan are you on? (Please answer with A, B, C, or U): "; cin >> custPlanType; // 仅修改判断条件:对用户输入的字符转大写后再比较 if (toupper(custPlanType) == 'A' || toupper(custPlanType) == 'B' || toupper(custPlanType) == 'C' || toupper(custPlanType) == 'U') custPlnTypeValid = true; else cout << "ERROR: Incorrect data type entered." << endl; } }
补充说明:如果需要更严谨的写法,可以把
toupper(custPlanType)替换为toupper(static_cast<unsigned char>(custPlanType)),避免char为有符号类型时,负值传入toupper出现未定义行为,初学者直接写简化版本也可以正常运行。
内容的提问来源于stack exchange,提问作者Samantha Maxam
相关产品推荐
相关产品推荐

