Append an int to char*

本秂侑毒 提交于 2020-01-20 14:22:11

问题


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


回答1:


First convert the int to a 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():

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"



回答2:


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();




回答3:


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.

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



来源:https://stackoverflow.com/questions/347132/append-an-int-to-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!