Pergunta

Como você anexar um inteiro para um char* em c ++?

Foi útil?

Solução

Em primeiro lugar converter o int para um char* usando sprintf():

char integer_string[32];
int integer = 1234;

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

Em seguida, para anexá-lo para o outro char *, strcat() uso:

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"

Outras dicas

Você também pode usar stringstreams.

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

A cadeia pode ser acessado usando ss.str();

Algo como:

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

Você poderia simplificar len usando o comprimento máximo para um inteiro no seu sistema.

editar oops - não ver o "++". Ainda assim, é uma alternativa.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top