如何输入输出购物车中的商品名称、价格、数量?

How to input and output item names, price, and quantity in a shopping cart?

我正在尝试创建一个程序来提示用户输入商品名称、价格和数量。然后输出用户输入的信息。当我 运行 它使用输入:Chocolate Chips, 3, 1 时,它输出:

项目 1

输入项目名称:

巧克力

输入商品价格:

0

输入商品数量:

32599

应该输出:

项目 1

输入项目名称:

巧克力片

输入商品价格:

3

输入商品数量:

1

这是我的代码:

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;  
 }

正在替换

cin >> name;

getline (cin, name);

成功了。