在地图中有流方式吗? [英] Is there a Way to Stream in a Map?

查看:108
本文介绍了在地图中有流方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,地图条目以行分隔,键和值以':'分隔。例如:


one:1

two:2

three:3

four:4


我在ifstream中打开这个名为dict的代码,然后运行以下代码:

  ; 
map< string,int> mytest;


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

有更好的方法吗?有没有一个getline功能,可以剥离键的空格?

解决方案

@Jonathan Mee:实际上你的帖子真的很优雅遇到麻烦,如果解析格式不匹配)。因此我的答案是:没有更好的方法。 +1

 <$> $ <$> 

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


int main(){
std :: istringstream input(
one:1 \\\

two:2 \\\

three:3 \\\

four:4 \\\

无效键:5 \\\

invalid_value:6 6 \\\

);

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

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


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.)

解决方案

@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;
}

这篇关于在地图中有流方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆