C ++ Csv文件没有正确加载到向量,它似乎知道对象在那里但不显示它们

时间:2017-08-18 18:59:34

标签: c++ csv vector

我一直在尝试将*.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);
        };
    }
}

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

    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";

    }

这是methodfunctionnew shoe类中添加variables所需的Footwear

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;

}

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

1 个答案:

答案 0 :(得分:0)

根据您的需要而不是您的具体问题:考虑不要编写自己的自定义CSV解析器,而是使用预先存在的C ++ CSV解析器库。例如several popular ones on GitHub

这具有额外的好处,可以更好地抵御意外的输入设计(例如引用的数字)。