码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 输入ctrl+z 不能再使用cin的问题

时间:2014-09-27 17:51:50      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   ar   for   文件   

问题介绍: 程序步骤是开始往容器里面写数据,以Ctrl+Z来终止输入流,然后需要输入一个数据,来判断容器中是否有这个数据。

源代码如下:

 1 #include<iostream>
 2 #include<map>
 3 #include<string>
 4 #include<vector>
 5 using namespace std;
 6 int main()
 7 {
 8     map<string,vector<int> >my_map;
 9     string word;
10     string word_to_find;
11     vector<int> ivec;
12     while(cin >> word)
13        my_map[word].push_back(0);
14 
15     cout << "input a string you want to find:" << endl;
16     
17     cin >> word_to_find;
18     map<string,vector<int> >::iterator it = my_map.find(word_to_find);
19     if(it != my_map.end())
20     {
21         vector<int>::iterator it_vec = (it->second).begin();
22         cout << it->first << endl;
23         for(it_vec;it_vec != (it->second).end(); it_vec++)
24             cout << *it_vec << " ";
25         cout << endl;
26     }
27 }

当在第12行输入ctrl+z终止输入流的时候,第17行的cin语句是失效的,应该是ctrl+z(文件结束符)默认程序是不再需要输入的,所以后面的cin语句就是失效的。

我开始的想法是是不是ctrl+Z还是留在缓冲区的,需要刷新缓冲区(清楚数据流)才能重新输入,于是在14行的位置加入cout << endl;发现这是不管用的,经过在网上搜索,发现需要如下解决方案,需要加入cin.clear()和cin.sync().

 1 #include<iostream>
 2 #include<map>
 3 #include<string>
 4 #include<vector>
 5 using namespace std;
 6 int main()
 7 {
 8     map<string,vector<int> >my_map;
 9     string word;
10     string word_to_find;
11     vector<int> ivec;
12     while(cin >> word)
13        my_map[word].push_back(0);
14     
15     cin.clear();  // 更改cin的状态标示符
16     cin.sync();  // 清除缓存区的数据流
17     cout << "input a string you want to find:" << endl;
18     
19     cin >> word_to_find;
20     map<string,vector<int> >::iterator it = my_map.find(word_to_find);
21     if(it != my_map.end())
22     {
23         vector<int>::iterator it_vec = (it->second).begin();
24         cout << it->first << endl;
25         for(it_vec;it_vec != (it->second).end(); it_vec++)
26             cout << *it_vec << " ";
27         cout << endl;
28     }
29 }

 

C++ 输入ctrl+z 不能再使用cin的问题

标签:style   blog   color   io   os   使用   ar   for   文件   

原文地址:http://www.cnblogs.com/hubavyn/p/3996413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!