Guys,
In below code they are couple of issues.
(1) I am not able to read first key and value pair record from snmp.json file in my map, it just start reading after first record.
(2) After reading the value from file in current implementation it is not reading the value after whitespace.(i.e allen solley , so it will just read the allen). Below is the snmp.json format.

{

        "1.2.3.6.1.1.4.1":"EventDescr",
        "1.2.3.6.1.1.4.2":"EventObjectID",
        "1.2.3.6.1.1.4.3":"EventObjectType",
        "1.2.3.6.1.1.4.4":"Event Date and Time",
        "1.2.3.6.1.1.4.5":"Asset Location",
        "1.2.3.6.1.1.4.6":"Variable ID",

}

Here is the code:

Here is the code:

#include <string>
#include <fstream>
#include <sstream>
#include <istream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
#include<iostream>
#include<vector>
#include <utility>
//static build_translation_table(void);
using namespace std;
static int translation_table[256];
int main()
{
std::string line;
vector <string>v;
int key=0,value=0;
std::map<std::string, std::string> props;
std::ifstream file("snmp.json");
while(std::getline(file, line)) {
    std::string token;
    std::istringstream tokens(line);
    while(tokens >> token) {
        std::size_t pos = token.find(':');
        if(pos != std::string::npos) {
            props[token.substr(0, pos)] = token.substr(pos +1);

           //props.insert(std::pair<string,string>(token.substr(0, pos),token.substr(pos + 1)));
          //cout<<translation_table[token.substr(0, pos)]=token.substr(pos + 1) ;

        }
    }

}
v.reserve(props.size());

for( std::map<std::string, std::string>::const_iterator ii=props.begin(); ii!=props.end(); ++ii)
     {
cout<<(*ii).first << ": " << (*ii).second << endl;

v.push_back(((*ii).first));
/*if (props["1.2.3.6.1.1.4.1"]=="EventDescr")
 cout<<"Hurray";
    }*/

}

for(int i=0; i < v.size(); i++){
 cout<<v[i]<<endl;
}

Recommended Answers

All 3 Replies

You might have more success using the getline method on the stringstream. Perhaps something like this:

while(std::getline(file, line)) 
{
    if(line.size() > 0)
    {
        std::string tokena,tokenb;
        std::istringstream tokens(line);
        std::getline(tokens,tokena,':');
        std::getline(tokens,tokenb);
        props.emplace(std::pair<string,string>(tokena,tokenb));
        //cout<<translation_table[token.substr(0, pos)]=token.substr(pos + 1) ;
        }
    }
}

Thnaks for your replay, but my compiler doesn't support emplace.

Change props.emplace(std::pair<string,string>(tokena,tokenb)); to props.insert(std::pair<string,string>(tokena,tokenb));

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.