未初始化的变量,但我正在尝试接受变量的输入?

Unintialized variable but I'm trying to accept an input for a variable?

本文关键字:变量 输入 初始化      更新时间:2023-10-16

我正在尝试设置一个输入,该输入可以接收商品的价格和数量,并且它一直给我两个未初始化的变量错误,所以我在主下给他们一个变量 0,但它不会打印出输入,只是显示它们的值为 0?

int main() {
string partNumber;
string partDiscription;
int partQuantity = 0;
int partPrice = 0;
int getInvoiceAmount;
class Invoice;
cout << "Please enter part number: " << partNumber << endl;
getline(cin, partNumber);
cout << "Please enter part discription: " << partDiscription << endl;
getline(cin, partDiscription);
cout << "Please enter quantity of item: " << partQuantity << endl;
cin >> partQuantity;
cout << "Please enter price of item: " << partPrice << endl;
if (partQuantity < 0)
    partQuantity = 0;
if (partPrice < 0)
    partPrice = 0;

这是因为您尝试在初始化变量数据之前对其进行引用。你应该这样做

cout << "Please enter part number: " << endl;
getline(cin, partNumber);
cout << "Please enter part discription: " << endl;
getline(cin, partDiscription);
cout << "Please enter quantity of item: " << endl;
cin >> partQuantity;

这样,您就不会尝试引用尚未初始化的变量。