如何把cin的buffer清掉呢?

Cixy 2004-08-20 10:57:58

程序如下:

#include <iostream.h>

int main(int argc, char *argv[]){
char s[10];

cout<<"1st 无效:";
cin>>s;
cout<<"---"<<s<<"---"<<endl<<"2nd 无效:";
cin.getline(s, 10);
cout<<"---"<<s<<"---"<<"how can i 无效 something for 2nd 无效?!!";

return 0;
}

程序运行时不给第二次输入机会,推断是cin的buffer内仍然有个'\r',可是如何把cin的buffer清掉呢?

找不到方法的我是这样做的

……
char tmpc = cin.get();
cin.getline(s2, 10);
if (tmpc=='\r')
s[0] = '\0';
else
{
s[0] = tmpc;
s[1] = '\0';
}
strcat(s, s2);
……

求比较比较“顺溜”点的方法,例如在getline之前放个clearbuffer的方法,可问题这个方法怎么写呢?!
...全文
172 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Cixy 2004-08-22
  • 打赏
  • 举报
回复
谢了,但是,我试过 ignore(256, '\10');为何这样写就不通呢?
Jinhao 2004-08-21
  • 打赏
  • 举报
回复
cout<<"---"<<s<<"---"<<endl<<"2nd 无效:";
cin.ignore(256, '\n');
cin.getline(s, 10);
cout<<"---"<<s<<"---"<<"how can i 无效 something for 2nd 无效?!!";
hellwolf 2004-08-21
  • 打赏
  • 举报
回复
no matching function for call to `std::basic_istream<char,std::char_traits<char> >::reflush()'

楼上的自己做的库?
dhfly 2004-08-21
  • 打赏
  • 举报
回复
cin.reflush();
dawning371 2004-08-21
  • 打赏
  • 举报
回复
ding
hcj2002 2004-08-21
  • 打赏
  • 举报
回复
#include <iostream.h>

int main(int argc, char *argv[]){
char s[10];

cout<<"1st 无效:";
cin>>s;
cout<<"---"<<s<<"---"<<endl<<"2nd 无效:";
cout.flush();
cin.getline(s, 10);
cout<<"---"<<s<<"---"<<"how can i 无效 something for 2nd 无效?!!";

return 0;
}

apprentice111 2004-08-21
  • 打赏
  • 举报
回复
cin>>a;
if( !cin.good() )
{
cin.clear();
cin.sync();
}

cin>>a;
hellwolf 2004-08-20
  • 打赏
  • 举报
回复
#include <iostream.h>

int main(int argc, char *argv[]){
char s[10];

cout<<"1st 无效:";
cin>>s;
cout<<"---"<<s<<"---"<<endl<<"2nd 无效:";
cin.get();
cin.getline(s, 10);
cout<<"---"<<s<<"---"<<"how can i 无效 something for 2nd 无效?!!";

return 0;
}

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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