load std::map from text file

前提是你 提交于 2019-11-30 04:09:01

问题


This is a very simple thing, so I want to keep it as simple as it sounds. All I want is to load a bunch of key-value paires from a file, and populate them in to a map. I do not really care how the text is structured, as long as it is easy to read.

What i have now is:

  • xml with xsd generated code (overkill)
  • Protocol buffer (also overkill)
  • INI style text file

I like the syntax of the INI file, but I not want to write a parser for that. It sounds to me like I would be doing something lots of people have done before me. Is there not some sort of library to read simple structured files like this?


回答1:


Since you seem to want the simplest thing humanly possible, I'm going to suggest something incredibly simple that may or may not work based on your map contents. If your map data values are strings that include spaces, this wont work. If they're strings without spaces, or numeric, you're set.

This isn't tested code, but it's close and simple so you should be fine even if it doesn't quite compile. Just change KeyType and ValueType to int, string, float, or whatever you're actually using in the file.

Set up file like:

key value
key2 value2
key3 value3
key4 value4

Read like:

KeyType key;
ValueType value;

std::map<KeyType, ValueType> myMap;
while (infile >> key >> value)
    myMap[key] = value;



回答2:


If you are in the MS world you can use

GetPrivateProfileSectionNames
GetPrivateProfileString
WritePrivateProfileString

to read from ini file or regestry. If you want to write Unicode make sure a newly created file gets the BOM of UTF16.



来源:https://stackoverflow.com/questions/10951447/load-stdmap-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!