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

时间:2017-01-11 22:20:07

标签: c++ c++11

我试图设置一个输入,它接受一个项目的价格和数量,它不断给我两个未初始化的变量错误,所以我给它们一个在主要下面的变量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;

1 个答案:

答案 0 :(得分: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;

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