C++ c++;读取文本文件并将其存储到vector

C++ c++;读取文本文件并将其存储到vector,c++,C++,我目前正在尝试读取此格式的文本文件(item.txt) itemId:itemDescription:itemCategory:itemSubCategory:amountPerUnit:itemQuantity:date 我想要的是读取文本文件,并根据我的预期输出将其存储在向量中。使用std::getline,您的方法是正确的。但是您应该逐行读取文件,然后将整行放入std::istringstream,然后可以使用std::getline标记该行 不能使用普通输入运算符>,因为它在空间上是分隔

我目前正在尝试读取此格式的文本文件(item.txt) itemId:itemDescription:itemCategory:itemSubCategory:amountPerUnit:itemQuantity:date
我想要的是读取文本文件,并根据我的预期输出将其存储在向量中。

使用
std::getline
,您的方法是正确的。但是您应该逐行读取文件,然后将整行放入
std::istringstream
,然后可以使用
std::getline
标记该行

不能使用普通输入运算符
>
,因为它在空间上是分隔的


范例

while (std::getline(readFile, line))
{
    std::istringstream iss(line);
    std::string temp;

    std::getline(iss, temp, ':');
    itemId = std::stoi(temp);

    std::getline(iss, itemDescription, ':');
    std::getline(iss, itemCategory, ':');
    std::getline(iss, itemSubCategory, ':');

    std::getline(iss, temp, ':');
    amountPerUnit = std::stod(temp);

    std::getline(iss, temp, ':');
    quantity = std::stoi(temp);

    std::getline(iss, date, ':');

    // Create object and add it to the vector
}

@用户3493435更新了我的答案您应该在此处使用
struct
。如果允许通过公共成员函数对私有成员进行任何修改,那么您也可以将它们全部公开。@ JFFRY,因为我更熟悉java,刚开始学习C++,我倾向于用java逻辑的方式来做事情,但是谢谢您的建议,我将在Struts上阅读。