2

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?

lakam99
  • 575
  • 4
  • 9
  • 24
  • 3
    Here's a hint - look into the [`%` (modulo) operator](http://en.wikipedia.org/wiki/Modulo_operator). – wkl Dec 01 '11 at 02:42

5 Answers5

4

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;
}
SundayMonday
  • 19,147
  • 29
  • 100
  • 154
  • 1
    +1. You could also add a quick check before the loop for negative numbers. If the number is negative, output or store the `-` and then `key = -key;` to make it positive before entering the loop. – Chris Parton Dec 01 '11 at 03:23
2

Why not read each input individually and handle them individually?

i.e.

cout<< " enter 5 digit key 0 to 9 \n";
char str[5];
cin.get(str, 5);

for (int i = 0; i < 5; ++i)
{
    //do something with str[i];
}
agenttom
  • 163
  • 1
  • 6
1

You may use the following code snippet, it will separate the digits in reverse order inwhile loop.

int i;
cin >> i;

while (i%10 != 0) 
{
  cout << i%10 << endl;
  i = i/10;
}
Taha
  • 1,086
  • 1
  • 10
  • 20
0

The while loop method will only take care of digits without zeroes.

Undo
  • 25,519
  • 37
  • 106
  • 129
0
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string str;
  cin >> str;

  size_t len = str.size();
  len = len > 5 ? 5 : len;

  for (size_t i=0; i<len; ++i)
  {
    cout << "digit " << i << " is: " << (str[i] - '0') << endl;
  }

  return 0;
}

I do it in this way

Dan
  • 3,221
  • 7
  • 27
  • 24