C++ csv 文件无法正确加载到矢量,它似乎知道对象在那里但不显示它们

C++ Csv file doesn't load to vector properly, it seems to know the objects are there but does not display them

本文关键字:对象 在那里 显示 文件 csv 加载 C++      更新时间:2023-10-16

我一直在尝试将*.csv文件读取到vector,但是它似乎不起作用,它的行为是有对象但不显示它们,如果它们是空的,它就会起作用。

这是加载*.csv文件的函数。

void loadShoes()
{
fstream shoes;
shoes.open("shoes.txt", ios::in);
string shoeId;
string valueId;
while (getline(shoes, shoeId, ','))
{
getline(shoes, valueId, ',');
ShoeMap[shoeId] = valueId;
if (shoeId == "ShoeLaceStyle")                                    
{
thefootwear.addShoe(ShoeMap);
};
}
}

此代码来自调用函数以加载到vector中然后在simple UI中显示的main

else if (userInput == 3)
{
for (int i = 0; i < thefootwear.vecNewShoe.size(); i++)
{
cout << i + 1 << " - " << thefootwear.vecNewShoe[i]->getShoeID() << "n";
}

cout << "nWhich Shoe would you like to view from the store?n";
cin >> userInput1;
cout << "ShoeID - " << thefootwear.vecNewShoe[userInput1 - 1]->getShoeID() << "n" << "ShoeName - " 
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeName() << "n" << "ShoeType - " 
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeType() << "n" << "ShoeSize - " 
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeSize() << "n" << "ShoeSoleStyle - "
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeSoleStyle() << "n" << "ShoeColour - " 
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeColour() << "n" << "ShoeLaceStyle - " 
<< thefootwear.vecNewShoe[userInput1 - 1]->getShoeLaceStyle() << "n";
}

这是在Footwear类中添加具有所需variablesnew shoemethodfunction

Shoe* Footwear::addShoe(map<string, string> ShoeMap)
{
Shoe* newShoe = new Shoe(ShoeMap["ShoeID"], ShoeMap["ShoeName"], ShoeMap["ShoeType"], ShoeMap["ShoeSize"], ShoeMap["ShoeSoleStyle"], ShoeMap["ShoeColour"], ShoeMap["ShoeLaceStyle"]);
vecNewShoe.push_back(newShoe);
return newShoe;
}

当我运行该程序时,它显示*.csv文件中当前正确的shoes数,但是它无法显示其相应的Shoe ID因此我无法访问与Shoes相关的变量。

说到您的需求而不是您的具体问题:考虑不要编写自己的自定义 CSV 解析器,而是使用预先存在的 C++ CSV 解析器库。例如,GitHub上有几个流行的。

这还有一个额外的好处,那就是对意外的输入设计(例如带引号的数字(更加可靠。