Yes, there is one, clean function available in the C standard library for this purpose....available in every C compiler I've used/owned.
From MSVC++ online help:
--------------------------------------...
Convert a long integer to a string:
char *_ltoa( long value, char *string, int radix );
Return Value: returns a pointer to string. There is no error return.
Parameters:
value -%26gt; Number to be converted
string -%26gt; String result
radix -%26gt; Base of value
Remarks: The _ltoa function converts the digits of value to a null-terminated character string and stores the result (up to 33 bytes) in string. The radix argument specifies the base of value, which must be in the range 2 – 36. If radix equals 10 and value is negative, the first character of the stored string is the minus sign (–).
Example:
/* ITOA.C: This program converts integers of various
* sizes to strings in various radixes.
*/
#include %26lt;stdlib.h%26gt;
#include %26lt;stdio.h%26gt;
void main( void )
{
char buffer[20];
int i = 3445;
long l = -344115L;
unsigned long ul = 1234567890UL;
_itoa( i, buffer, 10 );
printf( "String of integer %d (radix 10): %s\n", i, buffer );
_itoa( i, buffer, 16 );
printf( "String of integer %d (radix 16): 0x%s\n", i, buffer );
_itoa( i, buffer, 2 );
printf( "String of integer %d (radix 2): %s\n", i, buffer );
_ltoa( l, buffer, 16 );
printf( "String of long int %ld (radix 16): 0x%s\n", l,
buffer );
_ultoa( ul, buffer, 16 );
printf( "String of unsigned long %lu (radix 16): 0x%s\n", ul,
buffer );
}
Output:
String of integer 3445 (radix 10): 3445
String of integer 3445 (radix 16): 0xd75
String of integer 3445 (radix 2): 110101110101
String of long int -344115 (radix 16): 0xfffabfcd
String of unsigned long 1234567890 (radix 16): 0x499602d2
How do you convert a long to a string in C? Thanks?
i would use sprintf:
char buffer[20];
sprintf(buffer, "%u", value);
(you can also use snprintf, it's better but not available for every compiler).
Reply:Cast the long as a string
long i;
cout%26lt;%26lt;(string)i;
Reply:I think you can just type cast this. Try:
long toConv = 101;
string longString = (string) toBeConv;
longString is now a string that equals '101'
Sorted.
Reply:i am not sure if there is such a function...
although i know of its reverse (string to a long) through strtol(); and atol();
why not try to make the string variable assume the value of the long variable like this...
long X;
string Y;
Y = X;
but i am not sure if this works... i have studied C and C++ 7yrs ago...
:)
imperial
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment