When I enter start then the program outputs the else function even though I fulfilled the criteria, I have tried with && as well and it still didn\'t work. Any answe
The ||
works only in logical boolean expression.
From the standard (emphasis is mine):
5.15 Logical OR operator [expr.log.or]
The
||
operator groups left-to-right. The operands are both contextually converted tobool
(Clause 4). It returnstrue
if either of its operands istrue
, andfalse
otherwise.
So in input.find("end" || "End")
, it tries to convert "end"
and "End"
to bool
. And the operator ||
will return a bool
also.
Here to solve your problem you need to replace:
if (input.find("end" || "End") != std::string::npos)
by
if ( input.find("End") != std::string::npos ||
input.find("End") != std::string::npos )
And do the same in the second find
.
The argument of the function call
input.find("end" || "End")
has type bool and means that addess of string literal "end" or/and address of string literal "End" is not equal to zero. It is obvious that the both string literals have addresses that are not equal to zero. So the call is equivalent to
input.find(true)
The compiler finds an overloaded function find that is the most suitable for this argument. This function is
find( charT, c, size_tipe pos = 0 );
Value true is implicitly converted to value charT( 1 ) and the function tries to find char with value 1 in your string.
I'd recommend using regex instead for things like that: regex
Replace
if (input.find("end" || "End") != std::string::npos)
with:
if (input.find("end") != std::string::npos || input.find("End") != std::string::npos)
Similarly for your other if
.
It seems obvious what your expression means, but when you break it down it really doesn't make sense. find
expects a string, and "end" || "End"
is not a string.
the Logical or operator, ||
only works in boolean expressions.
For instance, if you had
bool A = true
bool B = false
bool C = A||B;
than you will have set bool C
to be True
. IT just takes 2 booleans, and returns true if either of those booleans is true. That's all logical or does.
You might want to try something like
if (input.find("end") != std::string::npos || input.find("End") != std::string::npos)
if (input.find("end" || "End") != std::string::npos) // ^^^^^^^^^^^^^^
The ||
operator is not being used correctly here. The righthand expression will return true because it is non-zero, then it will be returned. So the statement resolves to input.find("end")
. You need to use two separate conditional statements there:
if (input.find("end") != std::string::npos || input.find("End") != std::string::npos)