Domanda

Come aggiungeresti un numero intero a un char * in c ++?

È stato utile?

Soluzione

Prima converti l'int in un char * usando sprintf () :

char integer_string[32];
int integer = 1234;

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

Quindi per aggiungerlo al tuo altro carattere *, usa 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"

Altri suggerimenti

Puoi anche usare stringstreams.

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

È quindi possibile accedere alla stringa utilizzando ss.str();

Qualcosa del tipo:

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

Puoi semplificare len usando la lunghezza massima per un numero intero sul tuo sistema.

modifica oops - non ho visto " ++ " ;. Tuttavia, è un'alternativa.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top