你会

如何追加到char*的整数在C + +?

有帮助吗?

解决方案

首先使用char*整型转换为sprintf()

char integer_string[32];
int integer = 1234;

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

然后将其附加到其它字符*,使用strcat()

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"

其他提示

您也可以使用stringstreams。

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

的字符串然后可以使用ss.str();访问

是这样的:

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

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

修改的糟糕 - 没看到 “++”。不过,这是另一种选择。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top