例如,对于char*,您需要创建另一个对两者都足够长的变量。您可以“修复”输出字符串的长度,以消除超出字符串末尾的可能性。如果这样做,请注意使其足够大以容纳整数,否则您可能会发现 book+50 和 book+502 都以 book+50(截断)的形式出现。
以下是手动计算所需内存量的方法。这是最有效但容易出错的方法。
int a = 5;
char* ch1 = "Book";
int intVarSize = 11; // assumes 32-bit integer, in decimal, with possible leading -
int newStringLen = strlen(ch1) + intVarSize + 1; // 1 for the null terminator
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
snprintf(ch2, intVarSize, "%s%i", ch1, a);
ch2 现在包含组合文本。
另外,稍微不那么棘手,也更漂亮(但效率较低),您还可以进行 printf 的“试运行”以获得所需的长度:
int a = 5;
char* ch1 = "Book";
// do a trial run of snprintf with max length set to zero - this returns the number of bytes printed, but does not include the one byte null terminator (so add 1)
int newStringLen = 1 + snprintf(0, 0, "%s%i", ch1, a);
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
// do the actual printf with real parameters.
snprintf(ch2, newStringLen, "%s%i", ch1, a);
如果您的平台包含 asprintf,那么这会容易得多,因为 asprintf 会自动为您的新字符串分配正确的内存量。
int a = 5;
char* ch1 = "Book";
char* ch2;
asprintf(ch2, "%s%i", ch1, a);
ch2 现在包含组合文本。
c++ 不那么繁琐,但我会留给其他人来描述。