简体   繁体   中英

map with key and pair values in c++

I have the following text file:

0x2c200000 -3 1
0x2c200002 1 0
0x2c200004 -3 1
0x2c200006 2 3
0x2c200008 -1 2
0x2c20000a -2 1
0x2c20000c 3 1

I try to make an std::map from this text file where the first column is the key and the second & third are a pair value. I am using this simple code to do that:

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

typedef std::pair<int,int> ffp;
FILE *map;
std::map<int, ffp > m_idmap;
std::map<int, int> m_onOffmap;

void IDTest_3() {

 // Init the Id maps

 map = fopen("test1.txt","r");
 if(map==NULL){
 std::cout << "Do not have idmap text file !" << std::endl;
 return;
}
int id,BarEndCap,Sampling;

for(unsigned i=0; i<23; ++i) {

   if ( fscanf(map, "%d %d %d", &id, &BarEndCap, &Sampling) !=3 )
     {
         std::cout << "Corrupted file ? "<<std::endl;
         return;
     }
//       m_onOffmap[BarEndCap] = Sampling;
   m_idmap[id] = std::make_pair(BarEndCap,Sampling);
 }

 fclose(map);

 std::cout << " Test Bar endcap " << BarEndCap << std::entl;
 }

When I compile this part of the code I get the message "Corrupted file ?" looks like my fscanf doesn't work perfectly. Do you have an idea what I am doing wrong?

You are trying to match hexadecimal numbers (the first column) with the %d specifier, which expects integers in base 10.

Try with %x (hexadecimal only) or %i (auto-detection of base) instead!

See std::fscanf's format specifiers for more information.

 std::cout << " Test Bar endcap " << BarEndCap << std::entl;

You have entl instead of endl . With that change, it compiles for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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