Ajouter un int à char *
Question
Comment ajouteriez-vous un entier à un char *
en c ++?
La solution
D'abord, convertissez l'int en un char *
en utilisant sprintf ()
:
char integer_string[32];
int integer = 1234;
sprintf(integer_string, "%d", integer);
Ensuite, pour l'ajouter à votre autre caractère *, utilisez 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"
Autres conseils
Vous pouvez également utiliser des stringstreams.
char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;
La chaîne est ensuite accessible à l'aide de ss.str ();
Quelque chose comme:
width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);
Vous pouvez simplifier la lecture en utilisant la longueur maximale d'un entier sur votre système.
modifier oops - n'a pas vu le "++". Pourtant, c'est une alternative.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow