简体   繁体   English

使用 C++ 中的键和对值映射

[英]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.我尝试从这个文本文件制作一个 std::map ,其中第一列是键,第二列和第三列是一对值。 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.看起来我的 fscanf 不能完美工作。 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.您正在尝试将十六进制数字(第一列)与%d说明符匹配,该说明符需要以 10 为基数的整数。

Try with %x (hexadecimal only) or %i (auto-detection of base) instead!尝试使用%x (仅十六进制)或%i (自动检测基数)代替!

See std::fscanf's format specifiers for more information.有关更多信息,请参阅std::fscanf's格式说明符

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

You have entl instead of endl .你有entl而不是endl With that change, it compiles for me.有了这个改变,它就为我编译了。

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

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