简体   繁体   English

C++ 解析文件并将内容存储到 map

[英]C++ parse a file and store contents into a map

I am new, I parsed this text file and I am trying to store its contents into a map and print them out.我是新手,我解析了这个文本文件,并试图将其内容存储到 map 中并打印出来。 I can't seem to get the itr to work.我似乎无法让 itr 工作。

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;

}

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;还有 std::map<int, int, long> 寄存器; does not make sense as maps can only store 2 values.没有意义,因为地图只能存储 2 个值。 So remove it.所以删除它。

Also, you should not use the following line in your code:此外,您不应在代码中使用以下行:

using namespace std;

...as it's considered as bad practice. ...因为它被认为是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM