Sum of a line of integers

Hey everyone, just started C++ this semester and loving it. Just came across a problem though than i am unsure of where to start.
To begin, the program is supposed to print out a shipping label.
The important part is that i have to create a barcode form the zipcode.
So I need to get the zipcode from the user, then add each digit together to get a sum, and turn that sum into a variable.
Im just not sure where to start to adding the zipcode together. Heres what I have so far.

#include <iostream>
#include <string>
using namespace std;
int main()
{
string name, city, state, streetAddress;
int zipCode;

cout<<"This program is designed to set up a mailing label."<<endl;
cout<<"To whom will you be sending to?"<<endl;
getline(cin,name);

cout<<"What is the street address?"<<endl;
getline(cin,streetAddress);

cout<<"What is city"<<endl;
getline(cin, city);

cout<<"What is the state?"<<endl;
getline(cin,state);

cout<<"What is the zip code?"<<endl;
cin>>zipCode;
}

Any help is appreciated!
Google around "c++ split integer into digits" and the like -- this will get you the individual digits from your zip code.

The other option is to read the zip as a string, then convert the individual characters into digits (by subtracting '0' from each).

Hope this helps!
Since you seem to want zipCode as an integer variable, for now as a first pass, it might be easier if you instead ask the user to enter zipCode's digits one by one (five zip integer variables). Then a sixth variable can be the zip digit sum.

The more proper but more complicated method would be what Duthomhas suggested, instead having one zipCode string variable, and then parsing each character of that string as an integer, and only then performing a summation. This way is trickier, but you'd definitely learn a bit more about the lang if you google it and figure it out. Try both ways!

(edit: now that I think about it, there's actually a third way that involves pure number manipulation. Hint: what operators have you learned so far?)

glhf

Last edited on
@icy1
No, you are asking the user to do extra, weird input to supply a common value? Why should user (professor) like your program when it behaves weirdly?

Input the entire zip at once, either as int or as string. Then split it up where the user cannot see.
Topic archived. No new replies allowed.