How to convert from const char* to unsigned int c++

#include <iostream>
#include <sstream>

const char* value = "1234567";
stringstream strValue;
strValue << value;

unsigned int intValue;
strValue >> intValue;

cout << value << endl;
cout << intValue << endl;

Output:

1234567

1234567


If you really want to convert a pointer to a constant character into an unsigned int then you should use in c++:

const char* p;
unsigned int i = reinterpret_cast<unsigned int>( p );

This converts the address to which the pointer points to into an unsigned integer.

If you want to convert the content to which the pointer points to into an unsigned int you should use:

const char* p;
unsigned int i = static_cast<unsigned int>( *p );

If you want to get an integer from a string, and hence interpret the const char* as a pointer to a const char array, you can use one of the solutions mentioned above.


The C way:

#include <stdlib.h>
int main() {
    const char *charVar = "16";
    unsigned int uintVar = 0;

    uintVar = atoi(charVar);

    return 0;
}

The C++ way:

#include <sstream>
int main() {
    istringstream myStream("16");
    unsigned int uintVar = 0;

    myStream >> uintVar;

    return 0;
}

Notice that in neither case did I check the return code of the conversion to make sure it actually worked.


What do you mean by convert?

If you are talking about reading an integer from the text, then you have several options.

Boost lexical cast: http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

String stream:

const char* x = "10";
int y;
stringstream s(x);
s >> y;

Or good old C functions atoi() and strtol()

Tags:

C++