Home > OS >  C parse a file and store contents into a map
C parse a file and store contents into a map

Time:02-17

I am new, I parsed this text file and I am trying to store its contents into a map and print them out. I can't seem to get the itr to work.

this is the text file

addq Src,Dest  
subq Src,Dest 
imulq Src,Dest 
salq Src,Dest 
sarq Src,Dest
shrq Src,Dest 
xorq Src,Dest 
andq Src,Dest 
orq Src,Dest 
incq Dest 
decq Dest 
negq Dest 
notq Dest
#include <iostream>

#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <iomanip>
using namespace std;

class CPU {
    
    map<int, int, long> registers;
    
    
};

class ALU{
    int add, sub, mul, divide;
    
};

int main(int argc, const char * argv[]) {
    string line;
    string ins, src, dest;
    ifstream myfile("/Users/feliperivas/Documents/CPUProject/CPUProject/instrunction.txt");
    map<string, string> registers;
    

    while(getline(myfile, line)){
        stringstream ss(line);
        getline(ss, ins,',');
        getline(ss, src,',');

        registers.insert(pair<string, string>(ins, src));
        cout << line << endl;

// for (auto itr = registers.begin();
//          itr != registers.end();   itr) {
//         cout << itr->first << '\t'
//              << itr->second << '\n';
    }
    

    return 0;

}

CodePudding user response:

This works:

map<string, string>::iterator itr;
for (itr = registers.begin(); itr != registers.end();   itr) 
{
    // " : " separates itr->first and itr->second. Can be changed.
    std::cout << itr->first << " : " << itr->second << std::endl;
}

Final code:

#include <iostream>

#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <iomanip>

class CPU 
{
    //std::map<int, int, long> registers;
};

class ALU 
{
    int add, sub, mul, divide;
};

int main(int argc, const char* argv[]) 
{
    std::string line;
    std::string ins, src, dest;
    std::ifstream myfile("input.txt");
    
    std::map<std::string, std::string> registers;

    while (getline(myfile, line)) 
    {
        std::stringstream ss(line);
        std::getline(ss, ins, ',');
        std::getline(ss, src, ',');

        registers.insert(std::pair<std::string, std::string>(ins, src));
    }

    std::map<std::string, std::string>::iterator itr;
    for (itr = registers.begin(); itr != registers.end();   itr) 
    {
        std::cout << itr->first << " : " << itr->second << std::endl;
    }

    return 0;
}

Also std::map<int, int, long> registers; does not make sense as maps can only store 2 values. So remove it.

Also, you should not use the following line in your code:

using namespace std;

...as it's considered as bad practice.

  •  Tags:  
  • c
  • Related