有没有一种方法可以在地图中进行流式传输?

3
我有一个以行分隔的地图条目文件,键和值之间用“:”分隔。类似于下面的内容:
one : 1 two : 2 three:3 four : 4
我使用 ifstream 打开此文件,并运行以下代码:
string key, value;
map< string, int > mytest;


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

有没有更好的方法来做这件事?是否有一种getline功能可以从键中去除空格?(我试图在没有boost的情况下完成此操作。)

2个回答

3

是的,你可以简单地将冒号放入一个垃圾变量。

string key, colon;
int value;

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

通过这个,你应该确保冒号被空格分隔,并且你的键不包含任何空格。否则它将被读取到键字符串中。或者你的一部分字符串将被读作冒号。

3
它会失败: "one:" 成为一个键。 - user2249683

2

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

编辑:

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

所以听起来最好的去除键值的方法是添加:key.erase( remove_if( key.begin(), key.end(), isspace ), key.end() );,否则保持功能不变? - Jonathan Mee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接