Agregar un int a char *
Pregunta
¿Cómo agregaría un entero a un char *
en c ++?
Solución
Primero convierta el int en un char *
usando sprintf ()
:
char integer_string[32];
int integer = 1234;
sprintf(integer_string, "%d", integer);
Luego, para agregarlo a su otro char *, use 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"
Otros consejos
También puedes usar cadenas de cadenas.
char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;
Se puede acceder a la cadena usando ss.str();
Algo así como:
width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);
Puede simplificar len utilizando la longitud máxima para un número entero en su sistema.
editar ¡Vaya! No vi el " ++ " ;. Aún así, es una alternativa.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow