I am having a great deal of difficulty matching strings that contain a ‘|’ (ascii 124) character in c++. In the following code method, each time it runs it always matches to the last if statement:
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…
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
you need:
as the expression
strComp == "D|A"is evaluated before the||operator so you getfalse || "D|M"ortrue || "D|M"which is not what you want.