Dołączenie int do znaku*

Jak dodać liczbę całkowitą do char* W c++?

Author: Vadim Kotov, 2008-12-07

3 answers

Najpierw przekonwertuj int na char* używając sprintf():

char integer_string[32];
int integer = 1234;

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

Następnie, aby dodać go do swojego drugiego znaku*, użyj 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"
 23
Author: Jeremy Ruten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 15:52:50

Można również użyć stringstreams.

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

Ciąg można następnie uzyskać za pomocą ss.str();

 9
Author: Sydius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 15:52:17

Coś w stylu:

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

Możesz uprościć len używając maksymalnej długości dla liczby całkowitej w Twoim systemie.

edit oops-nie widziałem"++". Ale to alternatywa.

 4
Author: Draemon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-07 02:50:26