+ 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!

23rd Jul 2021, 9:43 PM
Abhay
Abhay - avatar
2 Respostas
+ 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 *).
23rd Jul 2021, 10:39 PM
Mark
+ 1
✩✮★✮✩ and Mark Thank you very much .
23rd Jul 2021, 10:47 PM
Abhay
Abhay - avatar