Hi,
I'm using ultoa to convert an unsigned long to string
but I'm having trouble to find the opposite function that will turn my string back to unsigned long
Can anyone help me?
Thanks in advance
Avi123
Printable View
Hi,
I'm using ultoa to convert an unsigned long to string
but I'm having trouble to find the opposite function that will turn my string back to unsigned long
Can anyone help me?
Thanks in advance
Avi123
I've never seen that function 'ultoa', but you could use _atoi64 and then convert to an unsigned long.
If you write a C program, you can use sscanf:
If you write a C++ program, you can use strstream:Code:unsigned long atoul(const char *buff)
{
unsigned long r;
sscanf(buff,"%lu",&r);
return r;
}
Code:unsigned long atoul(const char *s)
{
istrstream istr(s);
unsigned long r;
if (!(istr>>r)) r=0;
return r;
}
atol() will convert a string to long.
Code:char num[] = "123";
long n = atol(num);
or
std::string num = "123";
long n = atol(num.c_str());
There are two issues when converting strings to numeric types: correctness and performance. The problem is that many people seem to concentrate on the latter and to forget correctness.
The strstream approach SuperKoko shows is a good idea in its essence, however it suffers from the same flaw as the good old atoi() does -- namely you cannot tell the difference between a string that doesn't represent a numeric type and a string that does represent zero.
I'd suggest using either sscanf() or a stream approach, but with a success/failure check!
Except that you should not use strstream (deprecated) but stringstream (istringstream in this case).
You can distinguish a string that does not represent a number, as you get a failure if the string has no digits. If the string has digits and then more characters, you can also generate a failure by attempting to read in more characters, and if any were read you know you have a failure.