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 answers would be appreciated.
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main ()
{
float timer;
bool end;
std::string input;
end = false;
cout << "Enter start then a number to count down from" << ".\n";
while (end == false){
cin >> input;
if (input.find("end" || "End") != std::string::npos)
end = true;
else if (input.find("start" || "restart" || "Start" || "Restart") != std::string::npos)
{
cin >> timer;
while (timer>0){
timer -= 0.1;
Sleep(100);
cout << timer << ".\n";
}
cout << "Finished! Enter restart then another number to perform another countdown, or enter end to close the program" << ".\n";
}
else
cout << "Enter start" << ".\n";
}
return 0;
}
The argument of the function call
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
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
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 toinput.find("end")
. You need to use two separate conditional statements there:the Logical or operator,
||
only works in boolean expressions.For instance, if you had
than you will have set
bool C
to beTrue
. 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
C++ simply doesn't work that way. When you write
the compiler sees the logical or on two non-null const char pointers, which results in the boolean value
true
. This is then interpreted as achar
with the value1
('\1'
) which is then searched in the string - certainly not what you intended. If you want to know if you string is in a set of strings, you could use:While maybe not the most efficient code in the world, but with a C++11 compiler you can also condense it into a single line like this:
Replace
with:
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.