[英]To read from file and store data in map c++
我正在尝试读取文件内容并将其存储在地图数据结构中,我试图跳过不包含在我的地图中的评论部分。 我无法按预期保持我的地图,我有点不知道如何继续。 我已经提到了我的地图应该是什么样子。 请建议我必须在代码中添加哪些更改。 感谢Advnc :)
输入文件:
# Filename: MyFile
# Revision: 107
Items Types count price
snacks junkfood
Mango fruit 5 50
strawbery fruit 10 50
carrot veggie
burger junkfood
beetroot veggie 4 20
cinnamon masala
预期的输出文件:存储在map<string, string> [key] [value]
Items -> Types count price
snacks -> junkfood
Mango -> fruit 5 50
strawbery -> fruit 10 50
carrot -> veggie
burger -> junkfood
beetroot -> veggie 4 20
cinnamon -> masala
CPP 文件:
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
typedef std::pair<std::string, std::string> attribute_pair;
void check(ifstream &inputFile, map<string, string> &diffm)
{
diffm.clear();
std::string line;
while (getline(inputFile, line))
{
std::stringstream ss(line);
attribute_pair attribute;
while (ss >> attribute.first >> attribute.second)
{
if (attribute.first != "#")
diffm[attribute.first] = attribute.second;
}
}
}
int main(int argc, char const *argv[])
{
map<string, string> list1;
if (argc >= 2)
{
std::ifstream inputFile(argv[1]);
check(inputFile, list1);
map<string, string>::iterator itr;
for (itr = list1.begin(); itr != list1.end(); itr++)
{
cout << itr->first << " " << itr->second << "\n";
}
}
else
{
std::cerr << "Usage <prog name here> <filename1 here> <filename2 here>\n";
return -2;
}
}
我感觉很慷慨,我在某种程度上猜测您的要求(特别是地图的价值部分应该如何)。 我没有测试过这段代码。
void check(ifstream &inputFile, map<string, string> &diffm)
{
diffm.clear();
std::string line;
while (getline(inputFile, line))
{
if (line.empty() || line[0] == '#')
{
// skip blank or comment lines
}
else
{
std::stringstream ss(line);
std::string key, value;
// read first string (key)
ss >> key;
// read rest of line (value)
getline(ss, value);
diffm[key] = value;
}
}
}
这是个错误
while (getline(inputFile, line, '\0'))
应该
while (getline(inputFile, line))
第一个读取由\0
字符终止的“行”,我严重怀疑这是您想要的。 您想要以\n
字符终止的行,这就是第二个版本所做的。
这说明了 Beta 提出的观点。 您尝试的第一件事是错误的,因此编写和测试其余代码是浪费时间。 您应该编写一小段代码(例如检查您是否可以一次读取一行文件),并且只有当您确定它正在工作时,您才应该继续执行其余的任务。 例如,在弄清楚如何一次读取一行文件之后,下一个任务应该是看看您是否可以跳过注释行。 看? 将任务分解成更小的任务并解决每个更小的任务,然后再进行下一个任务。 这是至关重要的。 解决不仅仅意味着编写和编译代码,还意味着编写代码并编写一些代码来检查它是否正常工作(比如一些std::cout << ...
代码)。
始终迈出小步(尤其是在学习时)。 一次编写 20 行代码可能会出错的地方太多了。 编写两行、三行或四行代码,测试该代码,然后仅在它工作时再编写一些代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.