通过字符比较设置字符串时出错,请求排查代码问题
你的C++分支判断问题分析与修复方案
嘿,我一眼就瞅出你代码里的问题啦!问题出在条件判断的写法上,咱们来一步步拆解:
你原来的条件写的是:
if (direction == 'o' || 'O')
这种写法是错的!因为逻辑或||的两边都得是完整的布尔表达式,而单独的'O'是一个字符常量,它的ASCII值非零,会被编译器当成true。这就导致不管你输入什么字符,这个条件永远成立,第一个分支永远会被执行。同理,第二个else if的条件也是一样的错误写法。
修复方案有两种,选你顺手的来:
方案1:补全完整的判断表达式
把每个条件都写成完整的比较语句,确保逻辑或两边都是有效的布尔判断:
#include <iostream> #include <string> using namespace std; int main() { char direction; string printDirection; cout << "Inbound or Outbound? (I or O)" << endl; cin >> direction; if (direction == 'o' || direction == 'O'){ printDirection = "Outbound"; } else if(direction == 'i' || direction == 'I'){ printDirection = "Inbound"; } else{ cout << "Error"; return 1; } cout << printDirection << endl; // 补全输出语句 return 0; }
方案2:统一转换大小写后判断(更简洁)
先把输入的字符转换成大写(或小写),再做一次判断,这样代码更清爽,也避免重复写多个比较:
#include <iostream> #include <string> #include <cctype> // 需包含此头文件使用toupper函数 using namespace std; int main() { char direction; string printDirection; cout << "Inbound or Outbound? (I or O)" << endl; cin >> direction; char upperDir = toupper(direction); // 统一转成大写 if (upperDir == 'O'){ printDirection = "Outbound"; } else if(upperDir == 'I'){ printDirection = "Inbound"; } else{ cout << "Error"; return 1; } cout << printDirection << endl; return 0; }
小提醒
你原来的代码最后printD...应该是没写完,记得补全输出语句,不然看不到最终结果哒!
内容的提问来源于stack exchange,提问作者thugnasty
相关产品推荐
相关产品推荐

