weixin_38204163 2017-07-29 06:10 采纳率: 0%
浏览 1322
已结题

[C++]向map中插入数据,关键字为string,值为list<int>

 #include<iostream>
#include<string>
#include<list>
#include<map>


int main()
{
    std::map<std::string, std::list<int>> words;
    std::string word;
    int temp;
    while (std::cin>>word)
    {
        std::list<int> lst;
        while (std::cin>>temp)
        {
            lst.emplace_back(temp);
        }
        words.insert(std::pair<std::string, std::list<int>>(word, lst));
    }
    for (const auto &a : words)
    {
        std::cout << a.first << "\n";
        for (const auto &b : a.second)
        {
            std::cout << b << " ";
        }
        std::cout << std::endl;
    }
}

设想用户输入时可以这样输入:
a 1 2 3 4 5 
b 1 2 3 4 5 
输出时为:
a
1 2 3 4 5 
b
1 2 3 4 5

但是在实际使用的时候输出为
a
1 2 3 4 5 

请问是什么原因,该怎么改进呢
  • 写回答

1条回答

  • s_listening 2017-07-29 08:42
    关注

    cin在读取int时来了一个char字符,使输入状态变成fail,后面就不能输入了,重置一下输入状态就好

    #include<iostream>
    #include<string>
    #include<list>
    #include<map>
    
    
    int main()
    {
        std::map<std::string, std::list<int>> words;
        std::string word;
        int temp;
        while (std::cin>>word)
        {
            std::list<int> lst;
            while (std::cin>>temp)
            {
                lst.emplace_back(temp);
            }
            if(!std::cin.eof())
                std::cin.clear();
            words.insert(std::pair<std::string, std::list<int>>(word, lst));
        }
        for (const auto &a : words)
        {
            std::cout << a.first << "\n";
            for (const auto &b : a.second)
            {
                std::cout << b << " ";
            }
            std::cout << std::endl;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败