Adding an int into middle of char* (In C)

80 views Asked by At

Was wondering how it were possible to have an int in the middle of a char*, as such:

char * winning_message =
"Congratulations, you have finished the game with a score of " + INT_HERE +
"                 Press any key to exit...                   ";
3

There are 3 answers

1
Jas On BEST ANSWER

With this:

char winning_message[128]; // make sure you have enough space!
sprintf(winning_message, "Congratulations, you have finished the game with a score of %i. Press any key to exit...", INT_HERE);
3
Jeremy Friesner On

Perhaps you are looking for something like this?

char buf[256];  // make sure this is big enough to hold your entire string!
sprintf(buf, "Congratulations, you have finished the game with a score of %i\nPress any key to exit...", INT_HERE);

Note that the above is unsafe in the sense that if your string ends up being longer than sizeof(buf), sprintf() will write past the end of it and corrupt your stack. To avoid that risk, you could call snprintf() instead:

char buf[256];  // make sure this is big enough to hold your entire string!
snprintf(buf, sizeof(buf), "Congratulations, you have finished the game with a score of %i\nPress any key to exit...", INT_HERE);

... the only downside is that snprintf() may not be available on every OS.

3
bukkojot On

You can use:

char * winning_message;
asprintf(&winning_message,"Congratulations, you have finished the game with a score of %d\nPress any key to exit...\n", INT_HERE);