为什么不能输入key,不能进行查找?

liufei315336300 2009-08-18 09:44:32
#include<iostream>
#include<vector>
using namespace std;
bool search(vector<int>::iterator iter1,
vector<int>::iterator iter2,
int key)
{
while(iter1!=iter2)
{
if(*iter1==key)
break;
else
++iter1;
}
if(iter1!=iter2)
return true;
else
{ return false;
cout<<"Cann't find key"<<endl;
}

}
int main()
{
vector<int> vec;
int t,key;
cout<<"Enter t to vector:"<<endl;
while(cin>>t)
{
vec.push_back(t);
}
cout<<"Enter key:"<<endl;
cin>>key;
cout<<search(vec.begin(),vec.end(),key)<<endl;
return 0;
}
...全文
56 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ylj103037496 2009-08-18
  • 打赏
  • 举报
回复
cin.clear();
cin>>key;
cout < <search(vec.begin(),vec.end(),key) < <endl;
return 0;

使用while(cin>>t),流里会有数据存在,当你cin>>key 就直接在流里拿数据了,所以你并没有输入的机会。
需要使用cin.clear()清空一下流。
结束while的输入要用ctrl+D。
肥多罗 2009-08-18
  • 打赏
  • 举报
回复
那就在输入时 按 ctrl+D 好了
  • 打赏
  • 举报
回复
关于cin的问题,1.刷新缓冲区
2.清空流的状态。
一般都没问题了
liufei315336300 2009-08-18
  • 打赏
  • 举报
回复
哦,谢谢,大家了,嘿嘿...
liufei315336300 2009-08-18
  • 打赏
  • 举报
回复
哦,谢谢,大家了,嘿嘿...
jinwei1984 2009-08-18
  • 打赏
  • 举报
回复
return false;
cout < <"Cann't find key" < <endl;

两句交换一下顺序吧, 返回了第二句都不执行了
jinwei1984 2009-08-18
  • 打赏
  • 举报
回复
cin.clear();
cin>>key;
cout < <search(vec.begin(),vec.end(),key) < <endl;
return 0;
wanjingwei 2009-08-18
  • 打赏
  • 举报
回复
顶楼上
redlives 2009-08-18
  • 打赏
  • 举报
回复
while(cin>>t)
{
vec.push_back(t);
}
一直循环输入容器,没有结束条件

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧