通过带分隔符的 ifstream 读取文件

Reading File through ifstream with delimiters

我正在尝试读取包含项目 ID、名称和描述的文本文件。它们由“-”字符分隔。该代码适用于第一行,但对于其余行,只有 ID 被正确读取,而名称和描述为空白。 这是我正在读取的数据文本文件的片段。

items.txt 文件:

1080000 - White Ninja Gloves - (no description)
1080001 - Red Ninja Gloves - (no description)
1080002 - Black Ninja Gloves - (no description)
1081000 - Red Ninja Gloves - (no description)

这是我的代码:

void GetItemData()
        {
            std::ifstream File("items.txt");
            std::string TempString;
            while (File.good())
            {
                ItemData itemData;
                getline(File, TempString);
                size_t pos = TempString.find('-');
                itemData.ID = stoi(TempString.substr(0, pos));
                size_t pos2 = TempString.find('-', pos + 1);
                itemData.name = TempString.substr(pos + 1, pos2 - (pos + 1));
                itemData.description = TempString.substr(pos2 + 1, TempString.length() - 1);
                itemsList.push_back(itemData);
            }
        }

这是输出:

您的代码中遗漏了 std::list<ItemData> itemsList;

#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <vector>

struct ItemData {
    int ID;
    std::string name;
    std::string description;
};

std::vector<ItemData> itemsList;

void GetItemData() {
    std::ifstream File("items.txt");
    std::string TempString;    
    while (File.good()) {
        ItemData itemData;
        getline(File, TempString);
        size_t pos = TempString.find('-');
        itemData.ID = stoi(TempString.substr(0, pos));
        size_t pos2 = TempString.find('-', pos + 1);
        itemData.name = TempString.substr(pos + 1, pos2 - (pos + 1));
        itemData.description = TempString.substr(pos2 + 1, TempString.length() - 1);
        itemsList.push_back(itemData);
    }
}

std::ostream& operator<<(std::ostream& os, const ItemData& item) {
    os << item.ID << " - " << item.name << " - " << item.description;
    return os;
}

void PrintFile() {
    GetItemData();
    std::ofstream file("out.txt");
    for(auto line : itemsList) {
        file << line << std::endl;
    }
}

int main() {
    PrintFile();
    return 0;
}

我调试了代码,它对我来说是正确的,如果这对你不起作用,那就是其他地方出了问题。