c - 添加一个 int 到 char* 的中间(在 C 中)

标签 c char-pointer

想知道怎么可能在 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() 可能不适用于所有操作系统。

关于c - 添加一个 int 到 char* 的中间(在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108509/

相关文章:

C++:cout 和指向 char 的指针的无法解释的行为

c - 未初始化的堆分配误解(代码有效——需要更正以消除 Valgrind 错误)

string - 从 D 中的 float 转换为 const(char)*

c++ - 如何根据 OpenGL 规范安全地确保(在任何平台上)正确实现 char* 类型?

CS50 复数无法编译

c - 即使 char 数组以 null 终止并经过检查, printf 也会吐出垃圾

c - 如何分配从函数返回的变量

c - 如何在 AVX 中对 16 位压缩整数使用融合乘法和加法

c - mpz_add() 在大型程序中导致段错误

c - 为什么会出现错误 "segmentation fault"?