3

マップエントリが行で区切られ、キーと値が「:」で区切られたファイルがあるので、次のようになります。

1 : 1
2 : 2
3 : 3
4 : 4

これを dict という ifstream で開き、次のコードを実行します。

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


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

これを行うより良い方法はありますか?キーからスペースを削除する getline 機能はありますか? (ブーストなしでこれをやろうとしています。)

4

2 に答える 2

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;
}
于 2013-09-17T17:04:54.670 に答える