How can I convert an integer to a string for inclusion in another string? eg, here's a try with typecasting that doesn't work:
Compiles fine but segfaults.Code:int main () { int x=5; char *str=(char*)x; printf("%s", str); }
How can I convert an integer to a string for inclusion in another string? eg, here's a try with typecasting that doesn't work:
Compiles fine but segfaults.Code:int main () { int x=5; char *str=(char*)x; printf("%s", str); }
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
Yes, it would crash. You are trying to read a string from locaiton 5 in memory.
To concatenate a number to a string, you need to convert the internal (binary) representation to a string, and then concatenate the string. An easy way to do that would be to use sprintf() to "print" the number into a string buffer - you could even do something like this:
Buffer would in this case contain a string "Test012.txt"Code:char buffer[100]; int n = 12; ... sprintf(buffer, "Test%03d.txt", n); ...
--
mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
You may want to thank about the following:
Code:#include <stdlib.h> /*Prototype */ char *itoa(int value, char *string, int radix);
which is compiler specific, orCode:itoa( num, strOut, 10 );
which is standard C.Code:sprintf( strOut, "%d", num );
ahh, now that was nice and simple (sprintf)...thanx
Last edited by MK27; 08-06-2008 at 09:59 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge