Search code examples
c++stringdelimiterifstream

Reading File through ifstream with delimiters


I am trying to read from a textfile that includes the id, name, and description of an item. They are delimited by the '-' character. The code works for the first line, but for the rest of the lines, only the ID is read properly while the name and description are blank. Here is a snippet from the data text file that I am reading from.

items.txt file:

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

This is my code:

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);
            }
        }

Here is the output:

Output


Solution

  • You missed std::list<ItemData> itemsList; from your code.

    #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;
    }
    

    I debug the code and it words for me, if this does not work for you, something else went wrong.