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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
/* IF YOU ARE GOING TO STUDY, YOU HAVE TO MAKE IT CLEANER AS POSSIBLE! */
#include<iostream>
#include<iomanip>
#include<string>
#include<vector> //It's an array, but thousand times better and faster, for all.
using namespace std;
//Identation is a good pratice.
class store
{
//Always add members first.
private:
/*
I changed some variable names for readability, that's very important,
and some of "signed" and "unsigned" comparisons.
*/
double total; //Here, you don't need, but if you want, remove the zero and add the propriety in the constructor
/*- warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 -*/
unsigned number; //unsigned-int, you wouldn't use -0 numbers.
double price;
vector<string> products_name; //The best pratice, vectors are very good!
vector<double> products_price; //They are resize-able
public:
store(int n) : total(0) //Initializing the variable!
{
number = n;
products_name.resize(n);
products_price.resize(n);
}
void setname()
{
cout << "Enter the name of the products:\n\n"; //I've edited for clarifying
for (unsigned i = 0; i < number; i++)
{
std::cout << "Name " << i+1 <<": "; //Note the +1, because the user will not know that an array starts with 0
getline(cin , products_name[i]);
}
}
void setprice()
{
cout << "Please enter the price for items:\n"; //I've edited for clarifying
for (unsigned i = 0; i < number; i++)
{
std::cout <<"$ "; //Only the dollar simbol...
cin >> price;
if(cin.fail())
{
//Exceptions are good.
throw -1;
}
cin.sync(); //That was missing. That's the "error-fixer". It just clean the stream
products_price[i] = price;
std::cout << std::endl;
}
}
void settotal()
{
for (unsigned i = 0; i < number; i++)
{
total += products_price[i];
}
}
void getinfo(){
cout << "Product's name: " << setw(15) << "Product's price:\n";
for (unsigned i = 0; i < number; i++){
cout << products_name[i] << setw(25) << products_price[i] << endl;
}
cout << "Total = " << total;
}
//You don't need deleteptr anymore! Vectors have destructors!
};
int main()
{
try
{
unsigned x;
cout << "Welcome to your grocery shopping calculator\n";
cout << "PLEASE ENTER: how many items you have bought: ";
cin >> x;
if(cin.fail())
{
throw -2;
}
cin.sync(); //Sync...
store cal(x);
cal.setname();
cal.setprice();
cal.settotal();
cal.getinfo();
cin.get();
cin.get();
return 0;
}
catch(int except) //not only int, BUT we ARE using int-s, so...
{
if(except == -3)
{
std::cout << "You entered an invalid number!";
}
cout << "You entered an invalid number!";
return except;
}
}
/*
That program can be better, but I'll need more time ;)
*/
|