您好我在创建GroceryItem类并使用函数接受和设置用户输入时遇到了一些麻烦。
目前,当我运行dataEntry函数时,编译器会在接受第一个函数的输入之前继续执行下一个函数。
我已经创建了一个测试牛奶对象来测试我的代码但它不允许我在移动到下一个输入提示之前输入数据。
一旦我能找出类函数,我还将创建一个对象数组和输入值。
我将非常感谢任何有关如何修复此课程和功能的建议!
#include <iostream>
using namespace std;
class GroceryItem{
private: int stockNumber;
double price = 0.0;
int quantity;
double totalValue;
double setPrice();
int setStockNum();
int setQuantity();
void setTotalValue();
public:
void dataEntry();
void displayValues();
};
int GroceryItem::setStockNum(){
int stock = 0;
cout << "Enter the stock number for the grocery item: ";
do {
cout << "Stock Number(1000-9999): ";
cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));
stockNumber = stock;
return stockNumber;
}
double GroceryItem::setPrice(){
double x = 0.0;
cout << "Enter the price of the item: ";
while (!(x > 0)) {
cout << "Please enter a positive number for price!";
cin >> x;
}
price = x;
return price;
}
int GroceryItem::setQuantity(){
int x = 0;
cout << "Enter the quantity in stock: ";
while (!(x > 0)){
cout << "Please enter a positive number for quantity!";
cin >> x;
}
quantity = x;
return quantity;
}
void GroceryItem::setTotalValue(){
totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
setStockNum();
system("pause");
setPrice();
system("pause");
setQuantity();
system("pause");
setTotalValue();
}
void GroceryItem::displayValues(){
cout << "Stock number: " << stockNumber;
cout << "\nItem price: " << price;
cout << "\nQuantity on hand: " << quantity;
cout << "\nTotal value of item: " << totalValue;
}
int main(){
GroceryItem Milk;
Milk.dataEntry();
Milk.displayValues();
system("pause");
return 0;
}
答案 0 :(得分:0)
老兄,注意while语句的条件,行
!(stock >= 1000 || stock <= 9999)
对于stock = 0,返回true(在这种情况下总是为true),因此程序不会进入循环。 也许你的意思是:
!(stock >= 1000 && stock <= 9999)
AND(&amp;&amp;)不是OR(||)