【发布时间】:2010-09-25 17:13:01
【问题描述】:
如何在 c++ 中将整数附加到 char*?
【问题讨论】:
如何在 c++ 中将整数附加到 char*?
【问题讨论】:
首先使用sprintf()将int转换为char*:
char integer_string[32];
int integer = 1234;
sprintf(integer_string, "%d", integer);
然后要将其附加到您的其他 char*,请使用 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"
【讨论】:
你也可以使用字符串流。
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。
edit 哎呀 - 没有看到“++”。不过,它是一种替代方案。
【讨论】: