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

有帮助吗?

解决方案 2

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top