简体   繁体   English

匹配“ |” (垂直线)C ++中的字符

[英]Matching '|' (Vertical Line) Charachter in C++

I am having a great deal of difficulty matching strings that contain a '|' 我很难匹配包含'|'的字符串 (ascii 124) character in c++. (ascii 124)在c ++中的字符。 In the following code method, each time it runs it always matches to the last if statement: 在以下代码方法中,每次运行时,它始终与最后的if语句匹配:

if (strComp == "D|A" || "D|M" || "A|D" || "M|D") {c = "010101";}

I have tried escaping the '|' 我尝试转义'|' symbol with '\\|' 带“ \\ |”的符号 which did not work. 这没有用。 Surprisingly I have found little information on this issue when searched around. 令人惊讶的是,在四处搜寻时,我发现的信息很少。 Is there just something else wrong with my code that I am overlooking? 我忽略的代码是否还有其他问题? It is a normal ascii character, part of me thinks that this should be way easier... 这是一个正常的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;
}

Thank you very much for your help! 非常感谢您的帮助! Justin 贾斯汀

Instead of 代替

strComp == "D|A" || "D|M" 

you need: 你需要:

strComp == "D|A" || strComp == "D|M"

as the expression strComp == "D|A" is evaluated before the || 因为表达式strComp == "D|A"||之前求值 operator so you get false || "D|M" 运算符,因此您会得到false || "D|M" false || "D|M" or true || "D|M" false || "D|M"true || "D|M" true || "D|M" which is not what you want. true || "D|M"不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM