how to read characters from an input

so I've been trying to figure out how I can access individual integers from a zip code that is inputted by the user and adding them up. I was thinking of using a loop where total = 0 and total = total + the number the number that is read in chronological order. my only problem is I don't know how to access the individual number from the zip code

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
#include <iostream> 
#include <iomanip>
#include <string> 
using namespace std; 

int main()
{
	int zip; 
	int total = 0; 

	cout << "Please input your 5 digit zip code: "; 
	cin >> zip; 
	cout << endl;

	cout <<  "Your zipcode is: " << zip << endl; 

	
	








return 0;
}


I've read to use something like get() or to use an array but we haven't covered arrays in class yet and they seem a bit confusing at the moment. Any ideas?
if you're just adding the numbers up it shouldn't matter the order of the numbers so you can take advantage of the numbers being in decimal.

To get the right digit of a number you want to get the modulus zip % 10 then you can add that to the total and divide the zip by 10 ( well probably assign the zip value to a temp then modify that. ) then repeat while the number is greater than 0.


If you wanted to access the actual digits in the string of characters you would have to input it as a string then call string[index] but that would be a character so you'd have to cast it to an int or subtract '0' from it.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
	int zip;
	int total;
	int temp;
	
	std::cout << "Please enter your zip: ";
	std::cin >> zip;
	
	temp = zip;
	
	while( temp > 0 )
	{
		total += temp % 10;
		temp /= 10;
	}
}
Topic archived. No new replies allowed.