Extracting individual digits from a long number problem

Hi all,
I'm trying to write a program that inputs an integer with multiple digits and outputs the number of odd, even, and zero digits in the original number.
I think I have most of it figured out, but I don't know how to make it read and evaluate individual digits. I assume I need to use a char variable somewhere...? Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>

using namespace std;

int main ()
{
long num = 0;
char ch;
int len = 0;
int i = 0;
int odd = 0;
int even = 0;
int zero = 0;

cout << "How many digits are in your number? ";
cin >> len;

cout << "Please enter a number with " << len << " digits: ";
cin >> num;

for (i=1; i<=len; i++)
{
//Here's where I don't know what to put, but I assume each 
//digit will be the variable ch of type char?

if (ch == 0)
zero++;

else if (ch % 2 == 0)
even++;

else
odd++;
}

cout << "The number of even digits is: " << even << endl;
cout << "The number of odd digits is: " << odd << endl;
cout << "The number of zero digits is: " << zero << endl;

system("pause");

return 0;
}


Also, is there a way to omit the input of the number of digits and just have the program tell how long the number is?

Thanks for you help! :)
There are two ways you can try this:

1)
Read the number in as a string and get the individual digits out using [] then convert them to numbers

2)
Read the number in as an int and get the individual digits out using % and /

I'd go with number 1 since it is much easier to scale and use IMO.

If you want to go with #2, go look up the % and / operators (modulus and integer division)
This is one of many variations on a classic homework problem. Go with #2.
Sorry, I'm still confused. I looked up the modulus and division operators and I think I understand how they work, but how do I use them to isolate each digit of the number to test if each digit is even, odd, or zero?
closed account (o3hC5Di1)
Hi there,

Have a look at following:

http://www.cplusplus.com/forum/beginner/30763/

Hope that helps.

All the best,
NwN
That's exactly what I was looking for! I guess I should have figured that out myself, but I'm still learning.

Thank you so much!
Topic archived. No new replies allowed.