【问题标题】:Reading File through ifstream with delimiters通过带有分隔符的 ifstream 读取文件
【发布时间】:2020-12-09 11:10:21
【问题描述】:

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

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

这是输出:

【问题讨论】:

  • 到目前为止你用过调试器吗?或者至少在迭代中打印一些值,例如getline 之后的TempString 和子字符串?
  • 无论如何,你应该拆分任务。具有从行创建条目的功能。更容易调试,因为您可以单独测试。

标签: c++ string delimiter ifstream


【解决方案1】:

您在代码中错过了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;
}

我调试了代码,它对我来说,如果这对你不起作用,那么还有其他问题。

【讨论】:

  • 是的,这不是问题。我也声明了一个外部向量,但将其打印到另一个文件中,只有 ID 和名称仍然会产生相同的结果。
  • @RodneyMuller 我刚刚编辑了源代码,现在它对我有用。如果它不适合你,应该给我更多的代码。
  • 我刚刚解决了这个问题。事实证明我没有正确打印到我的列表视图哈哈。我忘记增加占位符以将项目添加到名称的列表视图中。你说得对,那是另外一回事。谢谢你的回答!
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 2011-12-06
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多