在C++中,如何将整数附加到char*
?
首先使用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"
您还可以使用字符串流。
char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;
使用ss.str();
可以访问该字符串。
Something like:
width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);
您可以通过使用系统上整数的最大长度来简化len。
编辑 哎呀 - 没看到 "++"。不过,这仍然是一种选择。