+ 1
How to add int to string(char*) type ? [Solved]
Is the following good way to do it or is there a better solution ? #include <stdio.h> #include<string.h> int main() { char*c="test"; int f=5; char d[10]; sprintf(d,"%d",f); char e[20]; strcpy(e,c); strcat(e,d); const char *g=e; printf("%s",g); return 0; } Any help is much appreciated!
2 Respuestas
+ 3
Hi Abhay
You can simplify and avoid the creation of the additional arrays and the call to the copy and concatenation function.
For example, if you need the string "test5", you can simply write:
#include <stdio.h>
int main()
{
int f = 5;
char d[10];
sprintf(d, "test%d", f);
printf("%s\n", d);
return 0;
}
Then, if you need a pointer to this array just do "char s* = d". Please notice that "d" is already a pointer of the type (char *).