0

I need to compare all the lines in a file starting from the 3rd word (which is "TO") and if two lines are identical i have to merge them.

Example; this is my text file :

STATE a TO a x b b OUT 0 x 0 1
STATE b TO a x b b OUT 0 x 0 1
STATE c TO d b b b OUT 0 1 1 0 
STATE d TO c b b b OUT 0 1 1 0 
STATE e TO d b b b OUT 0 1 1 0 

this is the output that i need :

STATE ab TO a x b b OUT 0 x 0 1
STATE ce TO d b b b OUT 0 1 1 0 
STATE d TO c b b b OUT 0 1 1 0 

this is my code, it does delete second line if 2 are identical but I couldn't figure out how to merge the states (a, b ,c..) I think i have to use 2D map and i don't know how to use it under these conditions

#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <map>

using namespace std;

int main() {
    map<std::string, std::string> _map;
    map<string, string>::iterator it;
    string str1, str2;
    ifstream reader("Hajer.txt"); // my file
    while (getline(reader, str2)) {
        str1 = str2.substr(0, 8); // I compare them beginning from "TO"
        str2.erase(0, 8);
        _map[str2] = str1;        
    }
    reader.close();
    ofstream writer("New_Hajer.txt"); // the result
    for (it = _map.begin(); it != _map.end(); ++it)        
        writer << it->second << it->first << '\n';
    writer.close();
    return 0;
}

Thank you for your answers.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • [You shouldn't start a variable name with an underscore.](https://stackoverflow.com/q/228783/1332041) – acraig5075 Jan 13 '20 at 13:24
  • `str1 = str2.substr(0, 8); str2.erase(0, 8);` -- The `erase` is unnecessary. Just store the string starting at position 8 into the map. – PaulMcKenzie Jan 13 '20 at 13:38

1 Answers1

1

What you're doing is that each time you find a match you are replacing the previous map value with the new value.

_map[str2] = str1;

Instead, if _map[str2] already contains a value, then you want to append to the existing value.

auto found = _map.find(str2);

if (found == _map.end())
    _map[str2] = str1; // first occurrence
else
    found->second += str1.substr(6); // append subsequent occurrences
acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • Thank you it worked and I want to try something if there an x instead of 1 or 0, do you know how can i tell the program to read it as both ? For example these 2 lines should be similar : STATE a TO a x b b OUT 0 x 0 1 STATE b TO a x b b OUT 0 1 0 1 – Hajer Hraiech Sakly Jan 13 '20 at 14:54
  • You should ask a new question for that. The way to say "thank you" on SO is to vote up. The way to say "it works" is to accept the answer – acraig5075 Jan 13 '20 at 15:00