How do I split an int into its digits?

前端 未结 15 1505
渐次进展
渐次进展 2020-11-27 17:51

How can I split an int in c++ to its single numbers? For example, I\'d like to split 23 to 2 and 3.

15条回答
  •  攒了一身酷
    2020-11-27 18:05

    You can count how many digits you want to print first

    #include 
    #include 
    using namespace std;
    
    int main(){
    int number, result, counter=0, zeros;
    
    do{
        cout << "Introduce un numero entero: ";
      cin >> number;
    
      }while (number < 0);
    
      // We count how many digits we are going print
      for(int i = number; i > 0; i = i/10)
            counter++;
    
       while(number > 0){
    
           zeros = pow(10, counter - 1);
    
           result = number / zeros;
           number = number % zeros;
           counter--;
    
           //Muestra resultados
           cout << " " << result;
       }
       cout<

    }

提交回复
热议问题