question about Cin

i am writing a program the reads 5 digit zip code and calculates check digit.

take a look at a piece of my code

1
2
3
4
5
6
		cout << "Enter your zip code followed by space after each number then hit [Enter]: ";
			cin >> zip1 >> zip2 >> zip3>> zip4 >> zip5; //take the zip code numbers and store each number in a variable
			

	CheckDigit = (zip1 + zip2 + zip3 + zip4 + zip5)%10; //line 80 and 81 is to calculate he check digit
			CheckDigit = 10-CheckDigit;


that only accepts digits followed by a space but what if the user decided to put it all together like 12345 instead of 1 2 3 4 5??? thanksssssss

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
44
45
46
47
48
#include <iostream>
#include <string>

int sum_digits( int zip_code )
{
    if( zip_code < 10000 || zip_code > 99999 ) return 0 ; // invalid
    int sum_digits = 0 ;
    while( zip_code > 0 )
    {
        sum_digits += zip_code%10 ;
        zip_code /= 10 ;
    }

    return sum_digits ;
}

int check_sum( int zip_code ) { return 10 - sum_digits(zip_code)%10 ; }

std::string digit_to_string( int digit )
{
    static const std::string str[] = { "||:::", ":::||", "::|:|", "::||:", ":|::|",
                                       ":|:|:", ":||::", "|:::|", "|::|:", "|:|::" } ;

    if( digit < 0 || digit > 9 ) return "" ;
    else return str[digit] ;

}

std::string zip_code_to_string( int zip_code )
{
    if( zip_code < 10000 || zip_code > 99999 ) return "invalid" ;

    std::string result ;

    // http://en.cppreference.com/w/cpp/string/basic_string/to_string
    const std::string digits = std::to_string(zip_code) ;

    // https://msdn.microsoft.com/en-us/library/jj203382.aspx
    for( char c : digits ) result += digit_to_string( c - '0' ) ; // '7' - '0' == 7 etc.

    return result + digit_to_string( check_sum(zip_code) ) ;
}

int main()
{
    for( int zc : { 12345, 90807, 123456, 10001 } )
        std::cout << zc << ' ' << zip_code_to_string(zc) << '\n' ;
}

http://coliru.stacked-crooked.com/a/606d86551bc8be4d
Topic archived. No new replies allowed.