我在匹配包含'|'的字符串时遇到很大困难(ascii 124)c ++中的字符。在下面的代码方法中,每次运行它总是匹配最后一个if语句:
if (strComp == "D|A" || "D|M" || "A|D" || "M|D") {c = "010101";}
我试过逃避'|'符号'\ |'这没用。令人惊讶的是,我在搜索时发现这个问题的信息很少。我忽略了我的代码还有其他问题吗?这是一个正常的ascii角色,我认为这应该更容易......
string Code::comp(string strComp) {
string a = "0";
string c = "000000";
if (strComp.find('M') != -1) { a = "1"; }
if (strComp == "0") {c = "101010";}
if (strComp == "1") {c = "111111";}
if (strComp == "-1") {c = "111010";}
if (strComp == "D") {c = "001100";}
if (strComp == "A" || "M") {c = "110000";}
if (strComp == "!D") {c = "001101";}
if (strComp == "!A" || "!M") {c = "110001";}
if (strComp == "-D") {c = "001111";}
if (strComp == "-A" || "-M") {c = "110011";}
if (strComp == "D+1" || "1+D") {c = "011111";}
if (strComp == "A+1" || "M+1" || "1+A" || "1+M") {c = "110111";}
if (strComp == "D-1") {c = "001110";}
if (strComp == "A-1" || "M-1") {c = "110010";}
if (strComp == "D+A" || "D+M" || "A+D" || "M+D") {c = "000010";}
if (strComp == "D-A" || "D-M") {c = "010011";}
if (strComp == "A-D" || "M-D") {c = "000111";}
if (strComp == "D&A" || "D&M" || "A&D" || "M&D") {c = "000000";}
if (strComp == "D|A" || "D|M" || "A|D" || "M|D") {c = "010101";} // This matches every time
return a+c;
}
非常感谢你的帮助! 贾斯汀
答案 0 :(得分:7)
而不是
strComp == "D|A" || "D|M"
你需要:
strComp == "D|A" || strComp == "D|M"
因为在strComp == "D|A"
运算符之前评估了表达式||
,因此您得到的false || "D|M"
或true || "D|M"
不是您想要的。