添加一个 int 到 char* 的中间(在 C 中)
Adding an int into middle of char* (In C)
想知道如何在 char* 中间有一个 int,例如:
char * winning_message =
"Congratulations, you have finished the game with a score of " + INT_HERE +
" Press any key to exit... ";
有了这个:
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);
也许您正在寻找这样的东西?
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() 可能无法在每个 OS.
上使用
您可以使用:
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);
想知道如何在 char* 中间有一个 int,例如:
char * winning_message =
"Congratulations, you have finished the game with a score of " + INT_HERE +
" Press any key to exit... ";
有了这个:
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);
也许您正在寻找这样的东西?
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() 可能无法在每个 OS.
上使用您可以使用:
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);