Hello.

Here is an example.

std::string Main = "12word1"; for (i = 0; i < n; i++) if (Main[i] == '1') { std::cout << Main[i]; } 

In this case, two units will fall into the console, because they occur 2 times in the line. I write this:

 std::string Main = "12word1"; for (i = 0; i < n; i++) if (Main[i] == '1' || '2') { std::cout << Main[i]; } 

It seems that if an element of a string is 1 or 2 then output it, but instead of 1 2 1 it prints the entire string. Where is the mistake?

  • Hmm ... Interesting, thanks. - BlackOverlord 5:02
  • + remember that the priority of "==" is higher than that of "||" hence the decision from the 1st comment - ProkletyiPirat
  • And I thought such errors are obvious ... The compiler did not display warnings? - Alexey Lobanov
  • No, it was not. - BlackOverlord

2 answers 2

Try writing this:

 if ((Main[i] == '1') || (Main[i] == '2')) { std::cout << Main[i]; } 

    The error is that the expression '2' is always true.

     for (i = 0; i < n; i++) if ((Main[i] == '1') || (Main[i] == '2')) { std::cout << Main[i]; }