A string is just a sequence of ASCII characters. What you have to do is convert each numeric digit into its ASCII representation.
For one digit the operation is simple:
char cuatro = 4 + '0';
Do not forget that char
actually stores a number in one byte, then arithmetic operations are allowed.
Now ... How does the whole chain become? As I told you, you must recover digit by digit to apply the transformation. You can do this by dividing the number by 10.
To know how many digits the number has, you can use the logarithms:
int numDigitos = log10(4567)+1;
std::cout << numDigitos;
With this data you can already know how many iterations you need:
int numero = 4567;
for(; numDigitos > 0; numDigitos--)
{
int digito = numero % 10;
numero /= 10;
std::cout << digito;
}
Wow, it turns out that the digits are recovered backwards, from the least significant to the most significant ... It really is something that can be easily solved. You can apply recursion or invert the final string to get the final string ... Although since you already have the calculated number of digits you can use that data to make the correction:
char cadena[5] = {0};
int numero = 4567;
for(; numDigitos > 0; numDigitos--)
{
cadena[numDigitos] = numero % 10;
numero /= 10;
}
std::cout << cadena;
It is in your hand to adapt it to your exercise and use std::string
instead of char[]
.