[英]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 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()可能並非在每個操作系統上都可用。
有了這個:
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 * winning_message;
asprintf(&winning_message,"Congratulations, you have finished the game with a score of %d\nPress any key to exit...\n", INT_HERE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.