Search code examples
c++numbersdigits

How to separate digits from a number in C++?


I'm trying to find a way to get 5 digits separately from a whole number.

cin >> option;      // Option to enter a number(don't worry about this)
if (option == 1)    // The option(don't worry)
{
    cout << " enter 5 digit key 0 to 9 \n";
    readin(key);    // The input number that needs the digits to be separated
}

The code above just inputs the number, but I want to separate the digits somehow...But how?


Solution

  • something like this:

    // handle negative values
    key = ABS(key);
    
    while(key > 0)
    {
        // get the digit in the one's place (example: 12345 % 10 is 5)
        int digit = key % 10;
    
        // remove the digit in the one's place
        key /= 10;
    }