C++ Converting string to unsigned int
I have the following string:
sThis = "2154910440"; unsigned int iStart=atoi(sThis.c_str());
However the result is
iStart = 2147483647
Does anybody see my mistake?
atoi converts a string to an int. On your system, an int is 32 bits, and its max value is 2147483647. The value you are trying to convert falls outside this range, so the return value of atoi is undefined. Your implementation, I guess, returns the max value of an int in this case.
You could instead use atoll, which returns a long long, which is guaranteed to be at least 64 bits. Or you could use a function from the stoi/stol/stoll family, or their unsigned counterparts, which will actually give useful error reports on out of range values (and invalid values) in the form of exceptions.
Personally, I like boost::lexical_cast. Even though it appears a bit cumbersome, it can be used in a more general context. You can use it in templates and just forward the type argument instead of having to have specializations