c++ - 通过带有分隔符的 ifstream 读取文件
问题描述
我正在尝试从包含项目 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;
}
我调试了代码,它对我说的话,如果这对你不起作用,那就是其他地方出了问题。
推荐阅读
- javascript - jQuery git 版本
- php - Laravel 5 在没有 SSH 的共享主机上:如何将上传的文件直接存储到 public_html 文件夹?
- windows - 如何运行 Hardware Lab Kit Ndis 6.5 LWF Logo 测试?
- python - 一个错误
从使用 pyzillow - java - vertx-redis-client 3.7.0:如何使用 redis 事务
- javascript - 我想在表格行的一列中存储可变数据
- android - Google Play App Signing and signature level permission
- java - Finding Deci-Binary for given input
- java - Spring boot Resttemplate通过ssh隧道的动态代理设置连接不识别远程DNS
- postgresql - kafka 连接器 jdbc-sink 最后出现语法错误