C++ 将 int 附加到 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/347132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:48:30  来源:igfitidea点击:

Append an int to char*

c++integercharappend

提问by user37875

How would you append an integer to a char*in c++?

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

回答by Jeremy Ruten

First convert the int to a char*using sprintf():

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

char integer_string[32];
int integer = 1234;

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

Then to append it to your other char*, use strcat():

然后将其附加到您的其他字符 *,请使用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"

回答by Sydius

You could also use stringstreams.

您也可以使用字符串流。

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

The string can then be accessed using ss.str();

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

回答by Draemon

Something like:

就像是:

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

You could simplify len by using the maximum length for an integer on your system.

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

editoops - didn't see the "++". Still, it's an alternative.

编辑哎呀 - 没有看到“++”。尽管如此,它仍然是一种选择。