12

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

dimba
  • 26,717
  • 34
  • 141
  • 196

5 Answers5

19

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

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
10

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
  • 3,703
  • 2
  • 21
  • 43
  • 1
    And if you want non-decimal interpretation, see also: http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer – Martin Sep 30 '09 at 07:23
  • 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. –  Sep 30 '09 at 07:25
  • 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 Sep 30 '09 at 07:27
1

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
  • 63,815
  • 23
  • 109
  • 159
  • 1
    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 ;-) –  Sep 30 '09 at 07:30
  • That should be "Anyone using a scanf-family function in C++ - ..." –  Sep 30 '09 at 07:32
0

It works if you go via _atoi64

unsigned long l = _atoi64(str);

-3

How about int atoi ( const char * str ) ?

string s("123");
unsigned u = (unsigned)atoi(s.c_str());
Igor
  • 26,650
  • 27
  • 89
  • 114
  • 5
    This is not a good suggestion at all. He's specifically asked for "unsigned int" and mentions things like "_ultoa". The poster knows about atoi(), atol(), etc. These functions are all signed and recognize the - symbol, might handle overflow, etc. The right answer is to use functions like strtoul. – Armentage Apr 19 '11 at 04:31