tags:

views:

857

answers:

4

Is there a method that converts string to unsigned int? _ultoa exists but couldn't find the vise verse version...

+7  A: 

strtoul() is the one. And then again there are the old ones like atoi().

Michael Krelin - hacker
atoi doesn't do unsigned though, right? In the Windows CRT, it will return an error (ERANGE) in the event of overflow.
Cheeso
Cheeso, yes, for what I can tell by the "i", it's int ;-)
Michael Krelin - hacker
+8  A: 

Boost provides lexical_cast.

#include <boost/lexical_cast.hpp>
[...]
unsigned int x = boost::lexical_cast<unsigned int>(strVal);

Alternatively, you can use a stringstream (which is basically what lexical_cast does under the covers):

#include <sstream>
[...]
std::stringstream s(strVal);
unsigned int x;
s >> x;
Martin
And if you want non-decimal interpretation, see also: http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer
Martin
Am I the only person who loves stream insertion, but hates stream extraction? I'd use functions (such as this boost one, though to be honest I'd probably still use atoi without thinking) every time.
Steve314
Yeah, stream extraction is pretty ugly, especially since you can't initialise constants with it. It is also quite a bit more powerful though, as you can use manipulators to change your base, etc.
Martin
+2  A: 

How about int atoi ( const char * str ) ?

string s("123");
unsigned u = (unsigned)atoi(s.c_str());
Igor Oks
A: 

sscanf will do what you want.

char* myString = "123";  // Declare a string (c-style)
unsigned int myNumber;   // a number, where the answer will go.

sscanf(myString, "%u", &myNumber);  // Parse the String into the Number

printf("The number I got was %u\n", myNumber);  // Show the number, hopefully 123
abelenky
I hated the scanf family even back in C. It never did what I wanted it to do, and most times it caused a bug. It's OK if you know that the string matches your requirements - if you've already checked it or extracted it with other code - but in that case, why not just use atoi or whatever?Anyone using a scanf-family function - well, there are some crimes where no punishment can ever be too harsh ;-)
Steve314
That should be "Anyone using a scanf-family function in C++ - ..."
Steve314