I am trying to read file contents and store it in map data structure, where I am trying to skip comment section not be included in my map. I am unable to keep my map as expected, I am kind off clueless how to go ahead. I have mentioned how my map should look like. Please suggest me what changes I have to add in my code. Thanks in Advnc 🙂
Input file:
# 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
Expected output file:
Stored in 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 file:
#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;
}
}
>Solution :
I’m feeling generous, I am guessing somewhat at your requirements (particularly how the value part of the map is meant to be). I have not tested this code.
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;
}
}
}