Is there a Way to Stream in a Map?

怎甘沉沦 提交于 2019-12-10 18:03:26

问题


I have a file with map entries separated by line, and the keys and values separated by a ':' So something like:

one : 1
two : 2
three:3
four : 4

I open this in an ifstream called dict and I run the following code:

string key, value;
map< string, int > mytest;


while( getline( dict, key, ':' ).good() && getline( dict, value ).good() )
{
    mytest[key] = atoi( value.c_str() );
}

Is there a better way to do this? Is there a getline functionality that would strip spaces from the key? (I'm trying to do this without boost.)


回答1:


@Jonathan Mee: Actually your post is really elegant (you might get into trouble, if the parsed format does not match). Hence my answer is: There is no better way. +1

Edit:

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


int main() {
    std::istringstream input(
        "one : 1\n"
        "two : 2\n"
        "three:3\n"
        "four : 4\n"
        "invalid key : 5\n"
        "invalid_value : 6 6 \n"
        );

    std::string key;
    std::string value;
    std::map<std::string, int > map;

    while(std::getline(input, key, ':') && std::getline(input, value))
    {
        std::istringstream k(key);
        char sentinel;
        k >> key;
        if( ! k || k >> sentinel) std::cerr << "Invalid Key: " << key << std::endl;
        else {
            std::istringstream v(value);
            int i;
            v >> i;
            if( ! v || v >> sentinel) std::cerr << "Invalid value:" << value << std::endl;
            else {
                map[key] = i;
            }
        }
    }
    for(const auto& kv: map)
        std::cout << kv.first << " = " << kv.second << std::endl;
    return 0;
}



回答2:


Yes, you can just simply throw the colon into a garbage variable

string key, colon;
int value;

while(cin >> key >> colon >> value) 
   mytest[key] = value;

By this, you should may sure the colon is separated by white space and your key doesn't contain any white space. Otherwise it will be read inside the key string. Or your part of string will be read as colon.



来源:https://stackoverflow.com/questions/18855128/is-there-a-way-to-stream-in-a-map

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