Hello,
Can you tecll me how to to convert an integer variable into a string variable in C? any help would be greatly appreciated. Thank you .
Hello,
Can you tecll me how to to convert an integer variable into a string variable in C? any help would be greatly appreciated. Thank you .
ยป char *itoa(int value, char *buffer, int radix);
Converts an integer value to a null-terminated string using the specified radix and stores the result in the given buffer. If radix is 10 and value is negative the string is preceded by the minus sign (-). With any other radix, value is always considered unsigned.buffer should be large enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
Here is the example:
Code:#include <stdlib.h> // for itoa() call #include <stdio.h> // for printf() call int main() { int num = 123; char buf[5]; // convert 123 to string [buf] itoa(num, buf, 10); // print our string printf("%s\n", buf); return 0; }
Refer to following thread to get more help:
How to convert string to int
Hope this helps.
The difference between stupidity and genius is that genius has its limits. - Albert Einstein
What we think, we become (Please don't think you are a superhero and don't try to fly)
"SUCCESS IS NOT A DESTINATION , IT'S A JOURNEY"
Below is example code for Converting string to int, double and long:
Code:#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; double d; long l; i = atoi("1"); l = atol("11111111"); d = atof("11111.11111"); printf("%d %ld %f", i, l, d); return 0; }
hey heres a better way ... ( the original way, without using library functions)
you can convert a char type into int type by:
here ch must b a single digit character(0-9) (its not a string)
num=ch-48; // shifting the ASCII value 48 units back.
now use this approach in a loop to convert the whole string as:
int chartoint(char *k)
{
int i;
int l;
int j;
int t=0;
l=strlen(k);
cout<<endl<<l<<endl;
for(i=0;i<l;i++)
{
j=k[i]-48;
t=t+j*(int)pow(10,l-i-1);
}
return t;
}
pass it the string ... say (123) and it will return 123 in integertype;
Bookmarks