64.8k views
2 votes
Write a zip code class that encodes and decodes 5-digit bar codes used by the U.S. Postal Service on envelopes. The class should have two constructors. The first constructor should input the zip code as an integer, and the second constructor should input the zip code as a bar code string consisting of 0s and 1s, as described above. Although you have two ways to input the zip code, internally, the class should store the zip code using only one format (you may choose to store it as a bar code string or as a zip code number). The class should also have at least two public member functions, one to return the zip code as an integer, and the other to return the zip code in bar code format as a string. All helper functions should be declared private. Embed your class definition in a suitable test program. Your program should print an error message if an invalid bar code is passed to the constructor.

User Ali BARIN
by
5.9k points

1 Answer

5 votes

Answer:

#include<iostream>

#include<string>

using namespace std;

class zip_code

{

private:

int zipcode;

string get_string(int num)

{

string str="";

if(num == 0) return "11000";

if(num>7)

{

str.append("1");

num = num-7;

}

else

str.append("0");

if(num>4)

{

str.append("1");

num = num-4;

}

else

str.append("0");

if(num>2)

{

str.append("1");

num = num-2;

}

else

str.append("0");

if(num>1)

{

str.append("1");

num = num-1;

}

else

str.append("0");

str.append("0");

return str;

}

public:

zip_code(int barcode)

barcode>99999)

cout <<"Invalid Bar code passed to constructor." << endl;

else

zipcode = barcode;

zip_code(string barcode)

{

if(barcode.length()>27)

cout <<"Invalid Bar code passed to constructor." << endl;

else

{

int zipper = 0;

string str_local = barcode.substr(1,barcode.length()-2);

for(int i=0; i<str_local.length()-5; i+=5)

{

int local = 0;

local = 7*(str_local[i]-'0') +

4*(str_local[i+1]-'0') +

2*(str_local[i+2]-'0') +

1*(str_local[i+3]-'0');

if(local == 11) local = 0;

zipper = zipper*10 + local;

}

zipcode = zipper;

}

}

string getZipcode()

{

string str = "1";

int first = zipcode/10000;

int second = (zipcode - first*10000)/1000;

int third = (zipcode - first*10000-second*1000)/100;

int fourth = (zipcode - first*10000-second*1000-third*100)/10;

int fifith = (zipcode - first*10000-second*1000-third*100-fourth*10);

str.append(get_string(first));

str.append(get_string(second));

str.append(get_string(third));

str.append(get_string(fourth));

str.append(get_string(fifith));

str.append("1");

return str;

}

int get_zipCode()

{

return zipcode;

}

};

int main()

{

zip_code z1(123456);

zip_code z2(99504);

cout << z2.getZipcode() << endl;

system("pause");

return 0;

}

User SDIDSA
by
6.6k points