Hi, 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
Hi, 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
In C this can be done using atoi
which is also available to C++ via cstdlib
.
#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()
atoi
function will convert const char* to int, which can be implicitly converted to unsigned. This won't work for large integers that don't fit in int.
A more C++-ish way is to use strings and streams
#include <sstream>
#include <string>
int main()
{
std::string strVar;
unsigned uintVar;
std::istringstream in(strVar);
in >> uintVar;
}
An easier but nonstandard way would be to use boost's lexical cast.
HTH
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.
Without more information there is no way to properly answer this question. What are you trying to convert exactly? If charVar is an ascii representation of the string, then you can do like others have suggested and use stringstreams, atoi, sscanf, etc.
If you want the actual value pointed to by charVar, then instead you'd want something like:
intValue = (unsigned int)(*charVal);
Or if charVal is the pointer to the first byte of an unsigned integer then:
intValue = *((unsigned int*)(charVal));