I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck. I have a:
const char* charVar;
and i need to convert it to:
unsigned int uintVar;
How can it be done in C++?
Thanks
const char* is useful for pointer to a string that will not change. ie your program will print some string, like the same welcome messages every time it starts. The unsigned version is useful for pointer to a binary sequence you may want to write too a file.
You can convert a char array to an integer using atoi: char *in = "4793"; int out = atoi(in);
char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.
1) Add UINT_MAX + 1 to your signed number and store it in an unsigned variable. (this will convert the signed integer to an unsigned integer of same magnitude). 2) Unsigned number of same binary representation can be found by multiplying each digit in the binary representation by its place value and adding them up.
#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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With