How to separate digits from a number in C++?
Question
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;
}
OTHER TIPS
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];
}
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;
}
#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
The while loop method will only take care of digits without zeroes.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow