C++ 有办法在地图上显示流吗?

C++ 有办法在地图上显示流吗?,c++,map,istream,C++,Map,Istream,我有一个文件,其中地图条目以行分隔,键和值以“:”分隔,因此类似于: 一:1 二:2 三:3 4:4 我在一个名为dict的ifstream中打开它,并运行以下代码: string key, value; map< string, int > mytest; while( getline( dict, key, ':' ).good() && getline( dict, value ).good() ) { mytest[key] = atoi( val

我有一个文件,其中地图条目以行分隔,键和值以“:”分隔,因此类似于:

一:1
二:2
三: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() );
}
字符串键,值;
mapmytest;
while(getline(dict,key,,:').good()&&getline(dict,value.good())
{
mytest[key]=atoi(value.c_str());
}

有更好的方法吗?是否有一个getline功能可以从键中删除空格?(我尝试在没有boost的情况下执行此操作。)

是的,您只需将冒号扔到垃圾变量中即可

string key, colon;
int value;

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

这样,您应该可以确保冒号由空格分隔,并且您的键不包含任何空格。否则,它将在密钥字符串中读取。或者您的字符串部分将被读取为冒号。

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

编辑:

#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;
}
#包括
#包括
#包括
int main(){
std::istringstream输入(
“一:1\n”
“两个:2\n”
“三:3\n”
“四:4\n”
“无效密钥:5\n”
“无效的\u值:6\n”
);
std::字符串键;
std::字符串值;
地图;
while(std::getline(输入,键“:”)&&std::getline(输入,值))
{
std::istringstream k(键);
查尔哨兵;
k>>键;

如果(!k | | k>>sentinel)std::cerr>sentinel)std::cerr)它将失败:“一:”成为一个键,听起来去除我的键值的最好方法是添加:
key.erase(如果(key.begin()、key.end()、isspace)、key.end();
,否则保持功能不变?