Make a program that goes from Int to String

3

Make a program that goes from int = 123 to string = "123"

I did a program that does it with stringstream , but now they ask me to do it without that, with pure cycles, I tried to do it like this:

Cout<<"datos: ";
Cin>>datos;
Texto = datos;

But it's not valid, they ask for it with cycles, I've searched and can not find something, any suggestions?

Also if I do:

texto+=datos;

It brings me the ascii symbol and it's not what I want, I'm stuck.

    
asked by Jose Luis 18.04.2017 в 06:55
source

4 answers

3

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[] .

    
answered by 18.04.2017 / 07:26
source
4

An alternative is to divide and obtain digit by digit of the number you want to convert to string, every time you get a digit you add 48 in decimal or 0x30 in hexadecimal to convert it into the corresponding ascii character, that you concatenate it in a string and to finish you only return the chain.

string intToString(unsigned int number){
    string sNumber="";
    if(number==0)return "0";
    while(number>0){
        int digit=number%10;
        sNumber=(char)(digit+0x30)+sNumber;
        number=number/10;
    }
    return sNumber;
}


int main()
{
    unsigned int number=984567;
    string result=intToString(number);
    cout<<result<<endl;

    return 0;
}

It should be noted that this code only applies to whole numbers without sign.

    
answered by 18.04.2017 в 07:12
2

This code is very similar to eferion .

#include <iostream>

using namespace std;

int main() {

  bool negativo = false;

  int numero = 3458;
  string numero_string;

  if (numero < 0){

    negativo = true;
    numero =-numero;
  }


  if (numero == 0){
     numero_string = "0";
  }

  for(numero_string = ""; numero > 0; numero_string.insert(numero_string.begin(), numero %10+'0'), numero /=10);

  if (negativo){
      numero_string.insert(numero_string.begin(), '-');
  }

  std::cout << numero_string;

  return 0;
}
    
answered by 18.04.2017 в 08:56
2

The process to pass a number to a chain consists in obtaining the digit number to digit and saving that digit in the chain; for it:

  • We obtain the remainder of the division of the number between its numerical base.
  • The remainder will be the digit, which will be changed to character.
  • We divide the number by its number base.
  • If the number is not 0, we return to point 1.
  • The problem of the described process is that it generates the number in reverse order (we obtain the lower weight digits first), but it is easy to solve with recursion:

    void resuelve(int numero, int base, std::string &cadena)
    {
        if (numero)
        {
            resuelve(numero / base, base, cadena);
            std::string::value_type c = numero % base;
    
            if (c >= 0 && c <= 9)
                c += '0';
            else if (c >= 10 && c <= 36)
                (c -= 10) += 'A';
    
            cadena.append(1, c);
        }
    }
    
    std::string numero_a_cadena(int numero, int base)
    {
        std::string resultado{};
        resuelve(numero, base, resultado);
        return resultado;
    }
    

    The resuelve function is a recursive function that jumps to the most significant digit and adds it to the string provided as the third parameter, then continues with the recursion by adding the least significant digits until it returns to the original call, these would be some examples of use:

    std::cout << numero_a_cadena(51966, 2) << '\n';  // Muestra 1100101011111110
    std::cout << numero_a_cadena(51966, 8) << '\n';  // Muestra 145376
    std::cout << numero_a_cadena(51966, 10) << '\n'; // Muestra 51966
    std::cout << numero_a_cadena(51966, 16) << '\n'; // Muestra CAFE
    std::cout << numero_a_cadena(51966, 32) << '\n'; // Muestra 1INU
    

    You can see the code working in Wandbox 三 へ (へ ਊ) へ ハ ッ ハ ッ .

        
    answered by 19.04.2017 в 10:35