find() returns -1?

Nov 1, 2011 at 2:59am
I am using string::find() in the syntax that

1
2
3
4
int t;
int pos = 4; //some number
string somestring(somechar);
 t = somestring.find("1", pos); //whatever is in the quotations is irrelevant 


Variable t should equal either npos if it is not found or the position it is found in the string. However in the script i have written t = -1. I do not know how t could be a negative number unless npos is a negative number but npos is not negative in this case. Does anyone know why this is?
Nov 1, 2011 at 3:05am
In your implementation, std::string::npos is 2^n-1, but the largest positive that can be represented by int is 2^(n-1)-1. int(2^n-1) is -1.
Nov 1, 2011 at 3:24am
Im sorry I dont under stand. Firstly npos =18446744073709551615. Secondly 2^n-1 is only 1 if n = 1 and could never equal a negative number. Also I declare npos like follows:
static const size_t npos = -1;
I am not sure if this is correct
Nov 1, 2011 at 3:50am
n depends on your system. In your case, n=64.

npos is declared by std::string. You shouldn't declare it yourself.

The problem is that t is of a signed type and it should be of an unsigned type.


*Sigh* Having to explicitly state everything is such a bore.
Last edited on Nov 1, 2011 at 3:53am
Nov 1, 2011 at 11:42am
@helios It's all right what you said, but you stuck for an satisfying answer. Here it is:
Decalare the return value of std::string::find() always as std::string::size_type (or auto for C++11) which is the correct type for your platform. Then compare this return value with the constant std::string::npos.

1
2
3
4
5
6
7
const std::string str = "foobar";
const std::string::size_type pos = 4;
const std::string::size_type ret = str.find("1", pos);
if (ret != std::string::npos)
{
    std::cout << "match at position " << ret << std::endl;
}
Last edited on Nov 1, 2011 at 11:50am
Topic archived. No new replies allowed.