我正在尝试建立一个从列表中读取并将内容存储在并行向量中的库存系统。我的向量在我已包含在我的代码中的类中设置为公共成员。文本文件如下所示
1111
Dish Washer
20 250.50 550.50
2222
Micro Wave
75 150.00 400.00
3333
Cooking Range
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00
6236
Tacos
200 5.00 5.50
这是我的代码
int main()
{
char choice;
Inventory Stocksheet(5); // the included list has 5 items if a text file has more then it should scale fine
int id, ordered;
string name;
double manuprice, price;
ifstream data;
data.open("Inventory Data.txt");
if (data.fail())
{
cout << "Data sheet failed to open \n";
exit(1);
}
while (data >> id )
{
Stocksheet.itemID.push_back(id);
getline(data,name);
Stocksheet.itemName.push_back(name); // this is where my code fails
data >> ordered;
Stocksheet.pOrdered.push_back(ordered);
Stocksheet.pInstore.push_back(ordered);
data >> manuprice;
Stocksheet.manuPrice.push_back(manuprice);
data >> price;
Stocksheet.sellingPrice.push_back(price);
}
do
{
cout << " Your friendly neighborhood tool shack\n";
cout << "Select from the following options to proceed \n";
cout << "1. Check for item \n";
cout << "2. Sell an iem \n";
cout << "3. Print Report \n";
cout << "Input any number other than 1,2 or 3 to exit \n";
cout << "Selection : ";
cin >> choice; // think about sstream here
switch (choice)
{
case '1': checkforitem(Stocksheet);
break;
case '2': sellanitem(Stocksheet);
break;
case '3': printthereport(Stocksheet);
break;
default: cout << " ^-^ Exiting the shop. Have a fantastic day! ^-^ \n";
break;
}
}while ((choice == '1') || (choice == '2') || (choice == '3'));
data.close();
return 0;
}
我评论了我的代码中断的地方。在while循环中,数字id被推送到我的第一个向量,但名称为空,之后的每个值都留空。我的循环设置有问题吗?
答案 0 :(得分:3)
当您使用>>
运算符时,您会得到一个&#34;字&#34;类型的东西。它在空白处停止。那么当你调用getline
时,它会读取第一行末尾的换行符(上面有id)并停止。因此,name
为空。
您可以在切换到data.ignore()
之前致电getline
,这样可以处理换行符。请小心地将>>
运算符与getline
混合。它没有做你期望的事情。