【发布时间】: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