Stuck need help with Array's

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

46 Replies - 1419 Views - Last Post: 15 March 2018 - 02:56 PM Rate Topic: -----

#1 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Stuck need help with Array's

Posted 05 March 2018 - 05:54 PM

Hi, I need to implement the following into my code and need some help reviewing:

Use 2 arrays: one for the products, and one for the quantities.
Use loops to assign values to the arrays.
Use loops to read and print values from the arrays.
Reuse the functions that you developed in Week 2 and the customer class that you developed in Week 3. Changes can be done as needed.
Complete the following in your code:
*Provide a list of available products
*Ask the customer to select products and quantities
*Save the provided details in arrays
*Read from the arrays to print the order summary; that is, the products, *quantities, and the total price for each product
*Calculate and print the total price for the order


I already have an array for product line 188 of my code I need to figure out how to do one for the quantity and verify my array for the product look correct. Therefore, I need to store not only the product in an array but also the quantity. Then read it to the order summary. Please assist and help provide me with an understanding for this.


#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit
using namespace std;


class Customer
{
	string custName; // Customer name
	string custAddress; //Customer Address

public:
	void info()
	{
		cout << setw(10) << left << "Name" << custName << "\n"
			<< setw(10) << left << "Address" << custAddress << "\n" << endl;
	}
	void simpleInfo()
	{
		cout << "\nHello " << custName << "\nAddress: " << custAddress << endl;
	}
	std::string value() const {
		return custName;
	}

	Customer() {}
	~Customer() {}
	Customer(string n, string a) {
		custName = n;
		custAddress = a;
	}
}; // END OF CLASS

struct Beverage
{
	string name;	// The name
	int quantity{}; // The quantity
	double price{}; //The price

	void info()
	{
		cout << setw(10) << left << "Name" << name << "\n"
			<< setw(10) << left << "Price" << "$" << price << "\n"
			<< setw(10) << left << "Quantity" << quantity << "\n"
			<< setw(10) << left << "Total" << "$"
			<< quantity * price << "\n" << endl;
	}
	void simpleInfo()
	{
		cout << "Selection: " << name << ", price per unit: $" << price << endl;
	}

	Beverage() {}
	~Beverage() {}
	Beverage(string n, double p) {
		name = n;
		price = p;
	}
}; // END OF STRUCT

double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
bool isAllDigits(string input);
int getValidNumber(string text, int min, int max);
void doShopping();

Customer snafu()
{
	std::string custName;
	std::string custAddress;
	cout << "Please enter your name ==> ";
	std::getline(std::cin, custName);
	cout << "Please enter your address ==> ";
	std::getline(std::cin, custAddress);

	return Customer(custName, custAddress);
}


void displayMenu(string userName) //Menu function
{

	cout << endl << endl
		<< userName
		<< ", Please select the beverage you would like to purchase from the menu: "
		<< endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1.45" << endl;
	cout << "2 - Soda $2.98" << endl;
	cout << "3 - Iced Tea $3.29" << endl;
	cout << "X - Exit " << endl << endl;
}

int main(void)
{
	doShopping();

	return 0;
}


int getQuantity() //Quantity function
{
	int quantity = 0;
	cout << "Enter quantity : ";
	cin >> quantity;
	return quantity;
}


bool isAllDigits(string input)
{
	for (unsigned i = 0; i < input.length(); i++) {
		if (!isdigit(input[i])) {
			return false;
		}
	}
	return true;
}

int getValidNumber(string text, int min, int max)
{
	string input{};
	int num{};
	while (true)
	{
		cout << text << " [" << min << " - " << max << "]: ";
		getline(cin, input);

		stringstream ss(input);

		if (!isAllDigits(ss.str())) {
			cout << "\nInvalid input. Try again!" << endl;
		}
		else {
			if (isAllDigits(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "\nOut of range. Try again!" << endl;
				}
			}
		}
	}
	return num;
}


double totalCost(Beverage beverages[], int numOfBeverages)  //Total cost function
{
	double totalCost = 0;

	for (int i = 0; i < numOfBeverages; i++) {
		totalCost += (beverages[i].price*beverages[i].quantity);
	}
	return totalCost;

}


void orderSummary(Beverage beverages[], int numOfBeverages) //Summary function
{
	cout << "\n======= ORDER SUMMARY ====" << endl;
	cout << "Items selected" << endl << endl;
	for (int i = 0; i < numOfBeverages; i++) {
		// only show beverages that has at least one order
		if (beverages[i].quantity > 0) {
			beverages[i].info();
		}
	}
}


void doShopping() //Shopping function
{
	// declare our beverages 
	Beverage
		water("Water", 1.45),
		soda("Soda", 2.98),
		iceTea("Ice Tea", 3.29);

	// Beverage array to hold the beverages
	Beverage beverages[] = { water, soda, iceTea };

	char selection = ' ';

	Customer patron = snafu(); // get info, create patron
	patron.simpleInfo(); // greet patron 

						 /*string name = "";
						 string address = "";

						 //Ask user for her/his name
						 cout << "Please enter your name ==> ";
						 getline(cin, name);

						 cout << "Please enter your address ==> ";
						 getline(cin, address);

						 //display user name
						 cout << "Hello " << name << endl;
						 cout << "Address: " << address << endl;
						 */

	do
	{
		// display menu
		displayMenu(patron.value());

		// read user selection
		cout << "Your selection: ";
		cin >> selection;
		cin.get(); // takes last ENTER character in the stream

		switch (selection)
		{
		case '1':
			beverages[0].simpleInfo();
			// assuming the customer can shop at least 1 and max 100
			beverages[0].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '2':
			beverages[1].simpleInfo();
			beverages[1].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '3':
			beverages[2].simpleInfo();
			beverages[2].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you for your purchase " << patron.value() << ", Come back soon!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			cin.get();
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x'); // 'X' or 'x' displays the summary
	system("pause"); //Pauses the system until a key is hit, The the program will end.
}



Is This A Good Question/Topic? 0
  • +

Replies To: Stuck need help with Array's

#2 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7183
  • View blog
  • Posts: 14,970
  • Joined: 16-October 07

Re: Stuck need help with Array's

Posted 06 March 2018 - 06:34 AM

There's a whole lot of badness going on here, I'm afraid. Now that you've moved to the next step, it's only going to get more confusing.

I'm just going to throw some cleaned up code at you, then explain:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit

// using namespace std;

class Customer {
    const std::string name, address;
public:
    void info(std::ostream &) const;
    void simpleInfo(std::ostream &) const;
    std::string value() const;
    // no  Customer() {}
    // pointless ~Customer() {}
    Customer(const std::string &name, const std::string &address);
}; // pointless comment END OF CLASS

struct Beverage {
    const std::string name; // The name, um, duh
    // you don't seem to want this here int quantity;
    double price;

    void info(std::ostream &) const;
    void simpleInfo(std::ostream &) const;
    // no Beverage() {}
    Beverage(const std::string &name, double price);
};


// Use 2 arrays: one for the products
const int AVAILABLE_PRODUCTS_COUNT = 3;
const Beverage AVAILABLE_PRODUCTS[AVAILABLE_PRODUCTS_COUNT] = {
    Beverage("Water", 1.45),
    Beverage("Soda", 2.98),
    Beverage("Ice Tea", 3.29)
};

// , and one for the quantities.
typedef int Quantities[AVAILABLE_PRODUCTS_COUNT];


double totalCost(Quantities);
void orderSummary(Quantities);
bool isAllDigits(const std::string &);
int getValidNumber(const std::string &, int min, int max);
void doShopping();
std::string getStringFromUser(const std::string &prompt);
char getCharFromUser(const std::string &prompt);
Customer getCustomerFromUser();
void displayMenu(const Customer &);
void loadProductQuantity(const Beverage &, Quantities);
void doneShowOrder(const Customer &, Quantities);

int main(void) {
    // needless doShopping();
    Quantities ordered = { 0 };
    Customer patron = getCustomerFromUser(); 
    patron.simpleInfo(std::cout);

    bool done = false;
    while (!done) {
        displayMenu(patron);
        switch (getCharFromUser("Your selection: ")) {
        case '1':
            loadProductQuantity(AVAILABLE_PRODUCTS[0], ordered);
            break;
        case '2':
            loadProductQuantity(AVAILABLE_PRODUCTS[1], ordered);
            break;
        case '3':
            loadProductQuantity(AVAILABLE_PRODUCTS[2], ordered);
            break;
        case 'X': case 'x':
            done = true;
            break;
        default: 
            std::cout << "Invalid selection. Please try again";
            std::cin.get();
            // no break in the default case
        }
    }
    doneShowOrder(patron, ordered);

    return 0;
}

void orderSummary(Quantities ordered) {
    std::cout <<  std::endl;
    std::cout << "======= ORDER SUMMARY ====" << std::endl;
    std::cout << "Items selected" << std::endl;
    for (int i = 0; i < AVAILABLE_PRODUCTS_COUNT; i++) {
        // only show beverages that has at least one order
        if (ordered[i] > 0) {
            // print something for AVAILABLE_PRODUCTS[i] here
        }
    }
}



Your current code puts quantity in Beverage: this seems wrong. The menu also reinvents the wheel by printing the Beverage list hard coded, rather than reading from the array. You can fix that.

Here, the idea is that you have an array for number of items ordered. It is the same size as the available items list and starts out zeroed out. If a user orders beverage number 1, for example, you update the ordered amount at index 1 to reflect the amount ordered. I've included orderSummary to give you a better idea what I'm talking about.

I don't care for the info/simpleInfo thing much. You might be better off just letting other bits of the program read object data and decide how to display it.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#3 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 06 March 2018 - 02:33 PM

What is wrong with the

Quote

info
and

Quote

simpleinfo
also if I put all the code you gave in visual studio it gives errors with green underlines throughout like half the program I wanted to see how it looks and runs then implement into my code. Please help explain more.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7183
  • View blog
  • Posts: 14,970
  • Joined: 16-October 07

Re: Stuck need help with Array's

Posted 06 March 2018 - 04:49 PM

View Postjosephhoffman28, on 06 March 2018 - 04:33 PM, said:

What is wrong with the info and simpleinfo


They don't really tell you what they're doing, they are only called once, they make your code harder to follow.

View Postjosephhoffman28, on 06 March 2018 - 04:33 PM, said:

also if I put all the code you gave in visual studio it gives errors with green underlines throughout


Indeed. Its mostly forward declarations and enough code to give the gist of the thing. Filling the implementation code in is your job. It is only intended as a guide.

The point is really to show that Beverage shouldn't have quantity and to give an idea how a quantity array would work, according to your instructions.
Was This Post Helpful? 0
  • +
  • -

#5 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 09 March 2018 - 06:57 PM

Can someone review my code and make sure the arrays are appropriately being called and used. Any feedback on changes I need is[welcome. Code below:

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit
using namespace std;


class Customer
{
	string custName; // Customer name
	string custAddress; //Customer Address

public:
	void info()
	{
		cout << setw(10) << left << "Name" << custName << "\n"
			<< setw(10) << left << "Address" << custAddress << "\n" << endl;
	}
	void simpleInfo()
	{
		cout << "\nHello " << custName << "\nAddress: " << custAddress << endl;
	}
	std::string value() const {
		return custName;
	}

	Customer() {}
	~Customer() {}
	Customer(string n, string a) {
		custName = n;
		custAddress = a;
	}
}; // END OF CLASS

struct Beverage
{
	string name;	// The name
	int quantity{}; // The quantity
	double price{}; //The price

	void info()
	{
		cout << setw(10) << left << "Name" << name << "\n"
			<< setw(10) << left << "Price" << "$" << price << "\n"
			<< setw(10) << left << "Quantity" << quantity << "\n"
			<< setw(10) << left << "Total" << "$"
			<< quantity * price << "\n" << endl;
	}
	void simpleInfo()
	{
		cout << "Selection: " << name << ", price per unit: $" << price << endl;
	}

	Beverage() {}
	~Beverage() {}
	Beverage(string n, double p) {
		name = n;
		price = p;
	}
}; // END OF STRUCT

double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
bool isAllDigits(string input);
int getValidNumber(string text, int min, int max);
void doShopping();

Customer snafu()
{
	std::string custName;
	std::string custAddress;
	cout << "Please enter your name ==> ";
	std::getline(std::cin, custName);
	cout << "Please enter your address ==> ";
	std::getline(std::cin, custAddress);

	return Customer(custName, custAddress);
}


void displayMenu(string userName) //Menu function
{

	cout << endl << endl
		<< userName
		<< ", Please select the beverage you would like to purchase from the menu: "
		<< endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1.45" << endl;
	cout << "2 - Soda $2.98" << endl;
	cout << "3 - Iced Tea $3.29" << endl;
	cout << "X - Exit " << endl << endl;
}

int main(void)
{
	doShopping();

	return 0;
}


int getQuantity() //Quantity function
{
	int quantity = 0;
	cout << "Enter quantity : ";
	cin >> quantity;
	return quantity;
}


bool isAllDigits(string input)
{
	for (unsigned i = 0; i < input.length(); i++) {
		if (!isdigit(input[i])) {
			return false;
		}
	}
	return true;
}

int getValidNumber(string text, int min, int max)
{
	string input{};
	int num{};
	while (true)
	{
		cout << text << " [" << min << " - " << max << "]: ";
		getline(cin, input);

		stringstream ss(input);

		if (!isAllDigits(ss.str())) {
			cout << "\nInvalid input. Try again!" << endl;
		}
		else {
			if (isAllDigits(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "\nOut of range. Try again!" << endl;
				}
			}
		}
	}
	return num;
}


double totalCost(Beverage beverages[], int numOfBeverages)  //Total cost function
{
	double totalCost = 0;

	for (int i = 0; i < numOfBeverages; i++) {
		totalCost += (beverages[i].price*beverages[i].quantity);
	}
	return totalCost;

}


void orderSummary(Beverage beverages[], int numOfBeverages) //Summary function
{
	cout << "\n======= ORDER SUMMARY ====" << endl;
	cout << "Items selected" << endl << endl;
	for (int i = 0; i < numOfBeverages; i++) {
		// only show beverages that has at least one order
		if (beverages[i].quantity > 0) {
			beverages[i].info();
		}
	}
}


void doShopping() //Shopping function
{
	// Beverage array to hold the beverages
	Beverage beverages[]{ { "Water", 1.45 },{ "Soda", 2.98 },{ "Ice Tea", 3.29 } };
	int quantities[sizeof(beverages) / sizeof(beverages[0])]{};

	char selection = ' ';

	Customer patron = snafu(); // get info, create patron
	patron.simpleInfo(); // greet patron 

	do
	{
		// display menu
		displayMenu(patron.value());

		// read user selection
		cout << "Your selection: ";
		cin >> selection;
		cin.get(); // takes last ENTER character in the stream

		switch (selection)
		{
		case '1':
			beverages[0].simpleInfo();
			// assuming the customer can shop at least 1 and max 100
			beverages[0].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '2':
			beverages[1].simpleInfo();
			beverages[1].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '3':
			beverages[2].simpleInfo();
			beverages[2].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you for your purchase " << patron.value() << ", Come back soon!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			cin.get();
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x'); // 'X' or 'x' displays the summary
	system("pause"); //Pauses the system until a key is hit, The the program will end.
}


Was This Post Helpful? 0
  • +
  • -

#6 ndc85430   User is online

  • I think you'll find it's "Dr"
  • member icon

Reputation: 826
  • View blog
  • Posts: 3,340
  • Joined: 13-June 14

Re: Stuck need help with Array's

Posted 09 March 2018 - 10:51 PM

Why do you have a function called snafu? You should choose meaningful names because that helps readability. Having said that, you seem to have done this in most cases.

This post has been edited by ndc85430: 10 March 2018 - 02:05 AM

Was This Post Helpful? 0
  • +
  • -

#7 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 10 March 2018 - 07:43 AM

I have reviewed and edited my code to use meaningful names code is below:

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit
using namespace std;


class Customer
{
	string custName;
	string custAddress;

public:
	void custInfo()
	{
		cout << setw(10) << left << "Name" << custName << "\n"
			<< setw(10) << left << "Address" << custAddress << "\n" << endl;
	}
	void custWelcome()
	{
		cout << "\nHello " << custName << "\nAddress: " << custAddress << endl;
	}
	std::string custValue() const {
		return custName;
	}

	Customer(string n, string a) {
		custName = n;
		custAddress = a;
	}
};

struct Beverage
{
	string name;
	int quantity{};
	double price{};

	void bevInfo()
	{
		cout << setw(10) << left << "Name" << name << "\n"
			<< setw(10) << left << "Price" << "$" << price << "\n"
			<< setw(10) << left << "Quantity" << quantity << "\n"
			<< setw(10) << left << "Total" << "$"
			<< quantity * price << "\n" << endl;
	}
	void bevSelect()
	{
		cout << "Selection: " << name << ", price per unit: $" << price << endl;
	}

	Beverage(string n, double p) {
		name = n;
		price = p;
	}
};

double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
bool isAllDigits(string input);
int getValidNumber(string text, int min, int max);
void doShopping();

Customer patName()
{
	std::string custName;
	std::string custAddress;
	cout << "Please enter your name ==> ";
	std::getline(std::cin, custName);
	cout << "Please enter your address ==> ";
	std::getline(std::cin, custAddress);

	return Customer(custName, custAddress);
}


void displayMenu(string userName) //Menu function
{

	cout << endl << endl
		<< userName
		<< ", Please select the beverage you would like to purchase from the menu: "
		<< endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1.45" << endl;
	cout << "2 - Soda $2.98" << endl;
	cout << "3 - Iced Tea $3.29" << endl;
	cout << "X - Exit " << endl << endl;
}

int main(void)
{
	doShopping();

	return 0;
}


int getQuantity() //Quantity function
{
	int quantity = 0;
	cout << "Enter quantity : ";
	cin >> quantity;
	return quantity;
}


bool isAllDigits(string input)
{
	for (unsigned i = 0; i < input.length(); i++) {
		if (!isdigit(input[i])) {
			return false;
		}
	}
	return true;
}

int getValidNumber(string text, int min, int max) //Verification function
{
	string input{};
	int num{};
	while (true)
	{
		cout << text << " [" << min << " - " << max << "]: ";
		getline(cin, input);

		stringstream ss(input);

		if (!isAllDigits(ss.str())) {
			cout << "\nInvalid input. Try again!" << endl;
		}
		else {
			if (isAllDigits(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "\nOut of range. Try again!" << endl;
				}
			}
		}
	}
	return num;
}


double totalCost(Beverage beverages[], int numOfBeverages)  //Total cost function
{
	double totalCost = 0;

	for (int i = 0; i < numOfBeverages; i++) {
		totalCost += (beverages[i].price*beverages[i].quantity);
	}
	return totalCost;

}


void orderSummary(Beverage beverages[], int numOfBeverages) //Summary function
{
	cout << "\n======= ORDER SUMMARY ====" << endl;
	cout << "Items selected" << endl << endl;
	for (int i = 0; i < numOfBeverages; i++) {
		// only show beverages that has at least one order
		if (beverages[i].quantity > 0) {
			beverages[i].bevInfo();
		}
	}
}


void doShopping() //Shopping function
{
	// Beverage array to hold the beverages
	Beverage beverages[]{ { "Water", 1.45 },{ "Soda", 2.98 },{ "Ice Tea", 3.29 } };
	int quantities[sizeof(beverages) / sizeof(beverages[0])]{};

	char selection = ' ';

	Customer patron = patName(); // get info, create patron
	patron.custInfo(); // greet patron 

	do
	{
		// display menu
		displayMenu(patron.custValue());

		// read user selection
		cout << "Your selection: ";
		cin >> selection;
		cin.get(); // takes last ENTER character in the stream

		switch (selection)
		{
		case '1':
			beverages[0].bevInfo();
			// assuming the customer can shop at least 1 and max 100
			beverages[0].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '2':
			beverages[1].bevInfo();
			beverages[1].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '3':
			beverages[2].bevInfo();
			beverages[2].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you for your purchase " << patron.custValue() << ", Come back soon!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			cin.get();
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x'); // 'X' or 'x' displays the summary
	system("pause"); //Pauses the system until a key is hit, The the program will end.
}



Besides fixing that how does everything look? I am looking for constructive feedback. I am a beginner and want to be able to succeed in my class. So I would like any advise and feedback I can get. I am trying to make sure the arrays are being properly utilized along with this I want to make sure my code is clean and efficient.
Was This Post Helpful? 0
  • +
  • -

#8 jimblumberg   User is online

  • member icon

Reputation: 5488
  • View blog
  • Posts: 17,064
  • Joined: 25-December 09

Re: Stuck need help with Array's

Posted 10 March 2018 - 08:41 AM

Quote

I am trying to make sure the arrays are being properly utilized along with this I want to make sure my code is clean and efficient.

Well, IMO, you're failing on both of these objectives.

First you're not properly utilizing your arrays, you're compiler should be telling you about this issue if it's properly configured.
main.cpp warning: unused variable ‘quantities’ [-Wunused-variable]|


Second you have quite a bit of code duplication. If you were properly using your arrays this duplication would be eliminated.

Here is the duplication:
		switch (selection)
		{
		case '1':
			beverages[0].bevInfo();
			// assuming the customer can shop at least 1 and max 100
			beverages[0].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '2':
			beverages[1].bevInfo();
			beverages[1].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '3':
			beverages[2].bevInfo();
			beverages[2].quantity += getValidNumber("Enter quantity", 1, 100);
			break;


Notice the only differences are the index values of the arrays.

Jim
Was This Post Helpful? 0
  • +
  • -

#9 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 10 March 2018 - 08:52 PM

So what can I do to improve these issues? I could really use advise and help to structure it.

I just need some explanation and guidance on how to use my arrays properly to best structure my code.
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6218
  • View blog
  • Posts: 21,468
  • Joined: 05-May 12

Re: Stuck need help with Array's

Posted 11 March 2018 - 06:38 AM

Try:
int index = selection - '1';



Now what do you see about the relationship between the value of index and the indices you are using in each of your case statements? How can you use this to remove duplicate code?
Was This Post Helpful? 0
  • +
  • -

#11 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 11 March 2018 - 05:24 PM

I have changed a lot with my code from feedback. I am still encountering issues can you please take a look at my code and provide some guidance my project is due in two days s I am trying to get it done and make it efficient.

My code:

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit

class Customer {
	const std::string custName, custAddress;
public:
	void custInfo(std::ostream &) const
	{
		std::cout << "Name" << custName << "\n"
			"Address" << custAddress << "\n" << std::endl;
	}
	void custWelcome(std::ostream &) const
	{
		std::cout << "\nHello " << custName << "\nAddress: " << custAddress << std::endl;
	}
	std::string custValue() const;
	Customer(const std::string &custName, const std::string &custAddress);
};

struct Beverage {
	const std::string name;
	double price;

	void bevInfo(std::ostream &) const
	{
		std::cout << "Name" << name << "\n"
			<< "Price" << "$" << price << "\n"
			<< "Total" << "$" << std::endl;
	}
	void bevSelect(std::ostream &) const
	{
		std::cout << "Selection: " << name << ", price per unit: $" << price << std::endl;
	}
	Beverage(const std::string &name, double price);
};


const int AVAILABLE_PRODUCTS_COUNT = 3;
const Beverage AVAILABLE_PRODUCTS[AVAILABLE_PRODUCTS_COUNT] = {
	Beverage("Water", 1.45),
	Beverage("Soda", 2.98),
	Beverage("Ice Tea", 3.29)
};

typedef int Quantities[AVAILABLE_PRODUCTS_COUNT];


double totalCost(Quantities);
void orderSummary(Quantities);
std::string getStringFromUser(const std::string &prompt);
char getCharFromUser(const std::string &prompt);
Customer getCustomerFromUser();
void displayMenu(const Customer &);
void loadProductQuantity(const Beverage &, Quantities);
void doneShowOrder(const Customer &, Quantities);

Customer patName()
{
	std::string custName;
	std::string custAddress;
	std::cout << "Please enter your name ==> ";
	std::getline(std::cin, custName);
	std::cout << "Please enter your address ==> ";
	std::getline(std::cin, custAddress);

	return Customer(custName, custAddress);
}

int main(void) {
	Quantities ordered = { 0 };
	Customer patron = getCustomerFromUser();
	patron.custInfo(std::cout);

	bool done = false;
	while (!done) {
		displayMenu(patron);
		switch (getCharFromUser("Your selection: ")) {
		case '1':
			loadProductQuantity(AVAILABLE_PRODUCTS[0], ordered);
			break;
		case '2':
			loadProductQuantity(AVAILABLE_PRODUCTS[1], ordered);
			break;
		case '3':
			loadProductQuantity(AVAILABLE_PRODUCTS[2], ordered);
			break;
		case 'X': case 'x':
			done = true;
			break;
		default:
			std::cout << "Invalid selection. Please try again";
			std::cin.get();
			// no break in the default case
		}
	}
	doneShowOrder(patron, ordered);

	return 0;
}

void orderSummary(Quantities ordered) {
	std::cout << std::endl;
	std::cout << "======= ORDER SUMMARY ====" << std::endl;
	std::cout << "Items selected" << std::endl;
	for (int i = 0; i < AVAILABLE_PRODUCTS_COUNT; i++) {
		// only show beverages that has at least one order
		if (ordered[i] > 0) {
			// print something for AVAILABLE_PRODUCTS[i] here
		}
	}
}



I really apprieate any and all help. I look forward to hearing back from you.
Was This Post Helpful? 0
  • +
  • -

#12 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6218
  • View blog
  • Posts: 21,468
  • Joined: 05-May 12

Re: Stuck need help with Array's

Posted 11 March 2018 - 05:43 PM

Drop the Smurf naming convention. It may help with non-object oriented languages, but it only serves to obfuscate things in C++.

What is more readable?
class Animal
{
public:
    string animalGenus() const;
    string animalSpecies() const;
    int animalLifespan() const;
};


Or:
class Animal
{
public:
    string Genus() const;
    string Species() const;
    int Lifespan() const;
};



You still have duplicate code on lines 81-89. See post #8.
Was This Post Helpful? 0
  • +
  • -

#13 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6218
  • View blog
  • Posts: 21,468
  • Joined: 05-May 12

Re: Stuck need help with Array's

Posted 11 March 2018 - 05:53 PM

Your continued use of function prototypes with just types but no parameter names does not help make the code more readable. Instead, it confuses things more and only helps out the compiler, but not the human reader.

If you feel that is too much typing with having to put in the names, go with the older Pascal convention of declaring things top to bottom with main() at the bottom instead of the top. Little to no need for prototypes if you follow his style.

Your various class functions which take an ostream as a parameter don't actually use the stream that is passed in. I personally consider that a bug and/or a design problem.
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6218
  • View blog
  • Posts: 21,468
  • Joined: 05-May 12

Re: Stuck need help with Array's

Posted 11 March 2018 - 06:43 PM

View Postjosephhoffman28, on 11 March 2018 - 08:24 PM, said:

I am still encountering issues

What issues are you encountering? If you are getting compiler warnings or errors, post them here verbatim. If you are getting unexpected behavior, tell us what behavior you are seeing, and what behavior you were expecting.
Was This Post Helpful? 0
  • +
  • -

#15 josephhoffman28   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-February 18

Re: Stuck need help with Array's

Posted 11 March 2018 - 08:02 PM

I do understand it. I have been using feedback to make changes and am having issues with it.

Code:

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream> // stringstream
#include <cctype> // isalph, isdigit

class Customer {
	const std::string custName, custAddress;
public:
	void custInfo(std::ostream &) const
	{
		std::cout << "Name" << custName << "\n"
			"Address" << custAddress << "\n" << std::endl;
	}
	void custWelcome(std::ostream &) const
	{
		std::cout << "\nHello " << custName << "\nAddress: " << custAddress << std::endl;
	}
	std::string custValue() const;
	Customer(const std::string &custName, const std::string &custAddress);
};

struct Beverage {
	const std::string name;
	double price;

	void bevInfo(std::ostream &) const
	{
		std::cout << "Name" << name << "\n"
			<< "Price" << "$" << price << "\n"
			<< "Total" << "$" << std::endl;
	}
	void bevSelect(std::ostream &) const
	{
		std::cout << "Selection: " << name << ", price per unit: $" << price << std::endl;
	}
	Beverage(const std::string &name, double price);
};


const int AVAILABLE_PRODUCTS_COUNT = 3;
const Beverage AVAILABLE_PRODUCTS[AVAILABLE_PRODUCTS_COUNT] = {
	Beverage("Water", 1.45),
	Beverage("Soda", 2.98),
	Beverage("Ice Tea", 3.29)
};

typedef int Quantities[AVAILABLE_PRODUCTS_COUNT];


double totalCost(Quantities);
void orderSummary(Quantities);
std::string getStringFromUser(const std::string &prompt);
char getCharFromUser(const std::string &prompt);
Customer getCustomerFromUser();
void displayMenu(const Customer &);
void loadProductQuantity(const Beverage &, Quantities);
void doneShowOrder(const Customer &, Quantities);

Customer patName()
{
	std::string custName;
	std::string custAddress;
	std::cout << "Please enter your name ==> ";
	std::getline(std::cin, custName);
	std::cout << "Please enter your address ==> ";
	std::getline(std::cin, custAddress);

	return Customer(custName, custAddress);
}

int main(void) {
	Quantities ordered = { 0 };
	Customer patron = getCustomerFromUser();
	patron.custInfo(std::cout);

	bool done = false;
	while (!done) {
		displayMenu(patron);
		switch (getCharFromUser("Your selection: ")) {
		case '1':
			loadProductQuantity(AVAILABLE_PRODUCTS[0], ordered);
			break;
		case '2':
			loadProductQuantity(AVAILABLE_PRODUCTS[1], ordered);
			break;
		case '3':
			loadProductQuantity(AVAILABLE_PRODUCTS[2], ordered);
			break;
		case 'X': case 'x':
			done = true;
			break;
		default:
			std::cout << "Invalid selection. Please try again";
			std::cin.get();
			// no break in the default case
		}
	}
	doneShowOrder(patron, ordered);

	return 0;
}

void orderSummary(Quantities ordered) {
	std::cout << std::endl;
	std::cout << "======= ORDER SUMMARY ====" << std::endl;
	std::cout << "Items selected" << std::endl;
	for (int i = 0; i < AVAILABLE_PRODUCTS_COUNT; i++) {
		// only show beverages that has at least one order
		if (ordered[i] > 0) {
			// print something for AVAILABLE_PRODUCTS[i] here
		}
	}
}



I have errors on lines 19-20, 37 and 53-55 I have green lines. I am confused by what I am doing wrong or not doing I apologize I am new at this so trying to grasp it I really could use the help and advice.

Here are all the errors my compiler is kicking back.
/tmp/ccV1iQGV.o: In function `patName()':
:(/>.text+0x161): undefined reference to `Customer::Customer(std::string const&, std::string const&)'
/tmp/ccV1iQGV.o: In function `main':
:(/>.text.startup+0x1c): undefined reference to `getCustomerFromUser()'
:(/>.text.startup+0x7e): undefined reference to `displayMenu(Customer const&)'
:(/>.text.startup+0x9c): undefined reference to `getCharFromUser(std::string const&)'
:(/>.text.startup+0xd3): undefined reference to `loadProductQuantity(Beverage const&, int*)'
:(/>.text.startup+0xf3): undefined reference to `doneShowOrder(Customer const&, int*)'
:(/>.text.startup+0x11b): undefined reference to `loadProductQuantity(Beverage const&, int*)'
:(/>.text.startup+0x15b): undefined reference to `loadProductQuantity(Beverage const&, int*)'

Please look through and let me know.
/tmp/ccV1iQGV.o: In function `_GLOBAL__sub_I__Z7patNamev':
:(/>.text.startup+0x23a): undefined reference to `Beverage::Beverage(std::string const&, double)'
:(/>.text.startup+0x27b): undefined reference to `Beverage::Beverage(std::string const&, double)'
:(/>.text.startup+0x2b9): undefined reference to `Beverage::Beverage(std::string const&, double)'
collect2: error: ld returned 1 exit status
Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »