I am trying to create a program that prompts user for item name, price, and quantity. And then outputs the info entered by the user. When I run it using inputs: Chocolate Chips, 3, 1, it outputs:
Item1
Enter the item name:
Chocolate
Enter the item price:
0
Enter the item quantity:
32599
It should be outputting:
Item1
Enter the item name:
Chocolate Chips
Enter the item price:
3
Enter the item quantity:
1
Here is my code:
main.cpp
#include <iostream>
using namespace std;
#include "ItemToPurchase.h"
int main() {
ItemToPurchase item1;
ItemToPurchase item2;
string name;
int price;
int quantity;
cout << "Item 1" << endl;
cout << "Enter the item name: " << endl;
cin >> name;
item1.SetName(name);
cout << item1.GetName() << endl;
cout << "Enter the item price: " << endl;
cin >> price;
item1.SetPrice(price);
cout << item1.GetPrice() << endl;
cout << "Enter the item quantity: " << endl;
cin >> quantity;
item1.SetQuantity(quantity);
cout << item1.GetQuantity() << endl;
cin.ignore();
cout << "Item 2" << endl;
cout << "Enter the item name: " << endl;
cin >> name;
item2.SetName(name);
cout << item2.GetName() << endl;
cout << "Enter the item price: " << endl;
cin >> price;
item2.SetPrice(price);
cout << item2.GetPrice() << endl;
cout << "Enter the item quantity: " << endl;
cin >> quantity;
item2.SetQuantity(quantity);
cout << item2.GetQuantity() << endl;
return 0;
}
ItemToPurchase.h
#ifndef ITEM_TO_PURCHASE_H
#define ITEM_TO_PURCHASE_H
#include <string>
using namespace std;
class ItemToPurchase {
public:
ItemToPurchase();
void SetName(string name);
void SetPrice(int price);
void SetQuantity(int quantity);
string GetName();
int GetPrice();
int GetQuantity();
private:
string itemName;
int itemPrice;
int itemQuantity;
};
#endif
ItemToPurchase.cpp
#include <iostream>
using namespace std;
#include "ItemToPurchase.h"
ItemToPurchase::ItemToPurchase() { // Default constructor
itemName = "none"; // Default name: none indicates name was not set
itemPrice = 0; // Default price: 0 indicates price was not set
itemQuantity = 0; // Default quantity: 0 indicates quantity was not set
}
// Accessors
void ItemToPurchase::SetName(string name) {
itemName = name;
}
void ItemToPurchase::SetPrice(int price) {
itemPrice = price;
}
void ItemToPurchase::SetQuantity(int quantity) {
itemQuantity = quantity;
}
// Mutators
string ItemToPurchase::GetName() {
return itemName;
}
int ItemToPurchase::GetPrice() {
return itemPrice;
}
int ItemToPurchase::GetQuantity() {
return itemQuantity;
}
Replacing
cin >> name;
with
getline (cin, name);
did the trick.