我試圖製作一個清單系統,它從列表中讀取並將其存儲在並行向量中。我的向量在我的代碼中包含的類中設置爲公共成員。該文本文件看起來像這樣從文件中的下一行讀取C++
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循環中,數字標識被推送到我的第一個向量,但名稱爲空,並且之後的每個值都留空。我的循環是如何設置的?
不會發布爲答案,因爲它與您所問的內容有點偏離:您可能想考慮將數據分解成類似於線條向量的東西,這將更容易處理(隨機訪問任何一行都變得輕而易舉),特別是如果你將來需要做更多這樣的操作的話。 – 2016-04-24 01:14:10
@WilliamKappler我不知道如何去做這件事。我剛剛瞭解到矢量是什麼。到目前爲止,我關於矢量的唯一新事物是我的實驗室教師說:「不,你不能使用矢量或結構,你必須使用數組」。 – Callat
矢量基本上是一個數組,但是更友好的實現爲具有特徵的類比如託管調整大小和稍後確定大小的能力。你計算出你需要存儲多少行(應該是'\ n'字符的數量+ 1),將一個'std :: vector'調整到這個大小,然後讀到每個'\ n'同時寫入矢量的每個連續元素,直到您點擊輸入的結尾。實質上,您需要PHP的'explode()'的C++版本。我說這可能會拋開你的問題,因爲它從一個完全不同的編程軌道開始。 –
2016-04-24 01:32:38