gh33
gh33

Reputation: 13

str.find() seems to be ignoring the first character in a string

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

Answers (4)

Paolo Brandoli
Paolo Brandoli

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

0x26res
0x26res

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

BЈовић
BЈовић

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

Gareth McCaughan
Gareth McCaughan

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

Related Questions