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
2009-09-30 07:15:36
atoi doesn't do unsigned though, right? In the Windows CRT, it will return an error (ERANGE) in the event of overflow.
Cheeso
2010-03-25 02:43:09
Cheeso, yes, for what I can tell by the "i", it's int ;-)
Michael Krelin - hacker
2010-03-30 14:30:08
+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
2009-09-30 07:16:21
And if you want non-decimal interpretation, see also: http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer
Martin
2009-09-30 07:23:00
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
2009-09-30 07:25:11
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
2009-09-30 07:27:20
+2
A:
How about int atoi ( const char * str ) ?
string s("123");
unsigned u = (unsigned)atoi(s.c_str());
Igor Oks
2009-09-30 07:16:59
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
2009-09-30 07:16:59
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
2009-09-30 07:30:55