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 49 50 51 52 53 54 55 56 57 58 59 60
|
//libraries, macros, ect.
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
//class for exception
class myException {
public:
myException (string prod_name) : name (prod_name) {}
string get_name () {
return name;
}
private:
string name;
};
//declare functions
int get_product_id(int, string, int, string) throw (myException);
int main() {
int product_ids[] = {4,5,8,10,13};
string products[] = {"computer", "flash drive", "mouse", "printer", "camera"};
int total_products;
string search;
char answer;
//cout << get_product_id(product_ids, products, 5, "mouse") << endl;
//cout << get_product_id(product_ids, products, 5, "camera") << endl;
//cout << get_product_id(product_ids, products, 5, "laptop") << endl;
try {
do {
cout << "Enter the name you want to search: ";
getline (cin, search);
int prod_id = get_product_id (product_ids, products, total_products, search);
cout << "The id is: " << prod_id << endl;
cout << "Do you want to search another product? Y for Yes: ";
cin >> answer;
}while(answer=='y'||answer=='Y');
}
catch (myException name_not_found) {
cout << name_not_found.get_name() <<
" product is not found in products list." << endl;
exit(1);
}
}
int get_product_id(int ids[], string names[],
int num_products, string target) throw (myException) {
for(int i=0; i < num_products; i++) {
if(names[i] == target) {
return ids[i];
}
}
throw myException(target);
}
|