将一个整数附加到char*

26

在C++中,如何将整数附加到char*

3个回答

29

首先使用sprintf()将int转换为char*

char integer_string[32];
int integer = 1234;

sprintf(integer_string, "%d", integer);

然后使用strcat()将它附加到您的其他char*中:

char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string

strcat(other_string, integer_string); // other_string now contains "Integer: 1234"

如果sizeof(int)>4,则您的程序存在缓冲区溢出漏洞。 - Tom
应该使用snprintf和strncat,以确保安全。 - Brian C. Lane
为什么不直接使用sprintf完成所有操作呢?snprintf(other_string, 64, "整数: %d", integer); - Lodle
不要使用字符串的固定常量大小,你可能想使用像 <基础大小> + sizeof(int)3+1 这样的东西(3 = ceil(8log10(2)), 1 代表‘-’)。这应该总是有效的(也适用于128位整数等情况),并避免了不必要的大内存分配(可能不是问题)。 - mweerden
这是相当老的。我尝试过了,它在strcat和sprintf上显示“不安全使用”。任何最新的答案都会很好。 - Leo
显示剩余2条评论

10

您还可以使用字符串流。

char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;

使用ss.str();可以访问该字符串。


返回字符串而不是char * - vozman

4

Something like:

width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);

您可以通过使用系统上整数的最大长度来简化len。

编辑 哎呀 - 没看到 "++"。不过,这仍然是一种选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接