在switch()中,cin.getline()起不到相应的作用

angelcm51 2008-05-16 07:53:50
在C++中,用cin.getline进行字符串的输入..
但在switch()中,cin.getline()却起不到相应的作用,这是为什么?
写一简单的测试代码如下:
#include<iostream>
#include<cstring>
using namespace std;
#define N 100

int main()
{
int deriction;
char str[N];
cout<<"enter deriction: ";
cin>>deriction;
switch(deriction)
{
case 1: cout<<"enter string:";
cin.getline(str,N);
cout<<str;
cout<<"Input finished!!";
break;
case 2: cout<<"OK";
break;
default: cout<<"error!";
}
return 0;
}
...全文
147 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
angelcm51 2008-05-17
  • 打赏
  • 举报
回复 1
在cin.getline(str, N);前加上fflush(stdin);
因为输入derection后还有'\n‘字符,getline会自动读取。

找到答案了~呵呵
pengzhixi 2008-05-16
  • 打赏
  • 举报
回复
建议直接用string类不要使用字符数组
pengzhixi 2008-05-16
  • 打赏
  • 举报
回复
switch(deriction)换成switch(cin>>deriction)试试,把上面的cin>>deriction去掉

64,668

社区成员

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

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