#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
请问是什么原因,该怎么改进呢
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;
}
}