1

想知道如何在 char* 中间有一个 int,如下所示:

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

3 回答 3

3

也许您正在寻找这样的东西?

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);

请注意,如果您的字符串最终比 sizeof(buf) 长,则上述内容是不安全的,sprintf() 将超过它的末尾并破坏您的堆栈。为了避免这种风险,您可以调用 snprintf() 代替:

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);

...唯一的缺点是 snprintf() 可能并非在每个操作系统上都可用。

于 2017-09-08T04:14:53.593 回答
1

有了这个:

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);
于 2017-09-08T04:14:11.503 回答
1

您可以使用:

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);
于 2017-09-08T04:15:23.697 回答