Reputation: 13
In the application where the complete code is
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Insert";
int kint = 0;
if (kint == 0 && str.find("Insert"))
{
cout << "found" << endl;
}
return 0;
}
No cout ever occurs. If you search for "nsert" instead then the cout does occur.
What am I missing?
Upvotes: 1
Views: 668
Reputation: 4750
find() returns the position of the found char. So the first char's position is 0, converted to false in boolean. You should compare with npos
if (kint == 0 && str.find("Insert") != str::npos)
{
cout << "found" << endl;
}
Upvotes: 0
Reputation: 13902
Actually it returns the position, which is 0 in your case. 0 is converted to false... look here
You need to check for str.find("Insert") != std::string::npos
in your if statement
Upvotes: 0
Reputation: 64223
Take a look what the find function returns :
Return Value The position of the first occurrence in the string of the searched content. If the content is not found, the member value npos is returned.
Since you search for "Insert" it returns 0 and the if fails
Upvotes: 1
Reputation: 19971
You're missing the fact that when find
doesn't return anything, it returns npos
not zero. A return value of 0 means that it found what it was looking for at index 0.
if (kint == 0 && str.find("Insert) != string::npos) { ... }
[NOTE: for about 15 seconds this answer claimed, wrongly, that str.find()
returns str.end()
on failure. This was rubbish. My apologies if anyone read the wrong version and believed it.]
Upvotes: 6