bool res = false;
cout << "Enter word to search" << endl;
string search;
cin >> search;
for (i = 0; i<line; i++)
{
size_t found = (data[i]).find(" " + search + " ");
if (found != string::npos)//what is this line
{
res = true;
cout << data[i] << " " << found << endl;
}
}
What i am trying to figure out is what does found!=string::npos mean and is there another way to write it?
strstr lets you know if it is there or not using null==0 pointer as a boolean. If you need to know where it was, find is far superior. Sometimes, you just want to know if its in there.
You can't use something else if you want to check if your search didn't find a match.
First: the test results true if the blank delimited search word was found.
2nd: The statement "you can't use something else.." made me thinking. How about (found > string::npos)? IMO even == will do. Hint: see the 3rd to 5th word of your a. m. statement.
yea, its a design fubar. They chose to return the array index where it is, which makes zero a no-go return value. If it had returned an iterator.... but no one asks me.
this works:
if (found < string::npos )
but it has zero merits over != which is more precise about what you want. The point is to get rid of the npos ugly, not to rewrite it and keep it in.
is risky and unportable to try to exploit npos being a negative number in a signed int result from find (int x = find (etc.. ) . It does work, but it may break on some systems where size_t is not the same bytesize as int. My work server broke on this, so I am sure that this is a real issue not just in theory.
In http://www.cplusplus.com/reference/string/string/npos
I find "static const size_t npos = -1; [...] This constant is defined with a value of -1" -- so this [-1] is not {-1} when compared with integers >= 0? :(
I am still learning.
Edit: ok, sorry, got it. Unsigned -1 = FFFFFFFFFFFFFFFF. No harm if the reference mentioned that detail.
First: the test results true if the blank delimited search word was found.
If what is being searched for is found, the function doesn't return string::npos. It returns the index of the first character of the found substring.
if the user entered word is "kumquat", what is passed into find in the OP's code is " kumquat ". A space is appended to the beginning and the end of the string before being used as the find parameter.
IMO even == will do.
If you want to do the INVERSE of a check for a substring being found, when when the substring is not found, then == string::npos works just fine. "Hey, did I come up a cropper looking for something?" If data[i] == "I like to eat a kumquat every day." a match is found.
The usual logic is structured to only check when something is FOUND. != string::npos
The exact meaning (of npos) depends on context, but it is generally used either as end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index.