-
July 25th, 2005, 03:17 AM
#1
ultoa
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
-
July 25th, 2005, 03:48 AM
#2
Re: ultoa
I've never seen that function 'ultoa', but you could use _atoi64 and then convert to an unsigned long.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
-
July 25th, 2005, 04:43 AM
#3
Re: ultoa
If you write a C program, you can use sscanf:
Code:
unsigned long atoul(const char *buff)
{
unsigned long r;
sscanf(buff,"%lu",&r);
return r;
}
If you write a C++ program, you can use strstream:
Code:
unsigned long atoul(const char *s)
{
istrstream istr(s);
unsigned long r;
if (!(istr>>r)) r=0;
return r;
}
-
July 25th, 2005, 05:08 AM
#4
Re: ultoa
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());
-
July 25th, 2005, 05:20 AM
#5
Re: ultoa
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!
-
July 25th, 2005, 05:30 AM
#6
Re: ultoa
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|