2008-12-07 37 views

Respuesta

22

Primero convertir el int a un char* usando sprintf():

char integer_string[32]; 
int integer = 1234; 

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

Entonces a lo añaden a su otro char *, utilice 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" 
+3

Esto también funcionará en C. – Sydius

+0

Tiene una vulnerabilidad de desbordamiento de búfer en sus manos si sizeof (int)> 4. – Tom

+0

Sí, esto es realmente inseguro. Al menos use strncat ... –

9

También es posible usar stringstreams.

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

La cadena entonces se puede acceder usando ss.str();

4

Algo así como:

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

Usted podría simplificar len mediante el uso de la longitud máxima de un número entero en su sistema.

editar oops - no vi el "++". Aún así, es una alternativa.