我有一个 char 数组和一些变量,我想使用 sprintf 来组合它们。
变量定义如下:
uint8_t var1;
char name1[20];
char textout1[40];
在程序的不同点,我使用 strcpy 来填充 name1。
strcpy(name1, "hello");
var1 也被赋值
var1 = 5;
然后我想使用 sprintf 将它们组合成一个 char 数组。
sprintf(textout1, "%s %u", name1, var1);
如果我现在打印textout1,我会得到
5
字符串/字符数组丢失。谁能弄清楚这是为什么吗? 单独打印 name1 数组给了我预期的“hello”,所以 strlcpy 工作正常。
最小代码示例:
#include <stdio.h>
#include <stdint.h>
uint8_t var1;
char name1[20];
char textout1[40];
int main() {
strcpy(name1, "hello");
var1 = 5;
sprintf(textout1, "%s %u", name1, var1);
printf(textout1);
printf(name1);
return 0;
}
最佳答案
字符串末尾缺少换行符或 fflush(stdout)。
printf() 将缓冲传递的字符串,直到遇到换行符。如果您想查看打印的内容,则必须添加
fflush(stdout);
在程序结束时。
关于c - sprintf 组合字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873253/