### Adding odd numbers in a line of input

First time posting. Been lurking for a while though, you guys have helped me out immensely so far though! Thanks :D
My question is about taking a line of input (32677) and adding all the odd numbers in it (3+2+7+7). All the questions similar to that in my search have to do with a range of odd numbers which I know how to do, just not how to take the actual numbers from the input. Hopefully I'm not asking something that's been answered a billion times before. Do I need to use strings to do this? Here's what I have so far but I'm pretty sure I'm missing something pretty basic.

#include <iostream>
#include <cmath>
using namespace std;

/*
* the sum of all odd digits of an input.
* (for example, if the input is 32677,
* the sum would be 3 + 7 + 7 = 17)
*/
int main(int argc, char** argv) {

int num;
int odd =0;

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

if (num%2!=0)
{
odd += num;
}

cout << "The sum of all the odd numbers is : " << odd << endl;
return 0;
}

With strings (don't forget to `#include <string> `)
 ``1234567891011`` ``````string in; cin >> in; int odd = 0; for(int i; i < in.length(); i++) if(in[i] >= '0' && in[i] <= '9'){ //is it a digit? int digit = in[i]-'0';//subtracting the ascii value for '0' gives the actual integer if(digit %2 != 0) odd += digit; }else{ cout << "what's this!?";//using a string does not ensure that only digits will be entered return 0; }``````

Without strings
 ``12345678`` ``````int n; cin >> n;//if the user enters a word, this gets stuck, or writes garbage to n, I don't remember int odd = 0; while(n > 0) { int digit = n % 10;//get the last decimal digit n /= 10;//erase the last digit from n; if(digit % 2 != 0) odd += digit; }``````
Last edited on
Worked beautifully, thanks. :)

I don't completely understand why lines 5 and 6 work.
Line 7 makes sense to me but why do you need an additional number's remainder of 10 and then divide the original number by ten and not use the original number in the if statement? Would you be able to give me a pseudo code example so I can understand the concept?
Try this, look at the output as well as the code, see if you understand what is going on:
 ``12345678910111213141516171819`` ``````#include using namespace std; int main() { int n = 314159265; while (n > 0) { cout << "n = " << n; // display current value of n int digit = n % 10; // get the last decimal digit n /= 10; // erase the last digit from n; cout << " digit = " << digit << endl; // display current digit } return 0; }``````

 ```n = 314159265 digit = 5 n = 31415926 digit = 6 n = 3141592 digit = 2 n = 314159 digit = 9 n = 31415 digit = 5 n = 3141 digit = 1 n = 314 digit = 4 n = 31 digit = 1 n = 3 digit = 3 ```

I assume you're referring to the second set of code hamsterman posted.

Some times it helps to work through the steps with pencil and paper.
 ``12`` ``````if(n % 2) odd += n % 10; n /= 10;``````