使用getline后如何使cin工作? [英] How to make cin work after using getline?
问题描述
因此,我使用cin.getline(str,10,'h')读取了一个字符串,如您所见,我使用了一个自定义定界符'h',并且希望最多读取9个字符.完成此操作后,我使用cin >> n将整数读入我的int变量n.
So, I read a string using cin.getline(str,10,'h') where as you can see I have used a custom delimiter 'h' and want to read a maximum of 9 characters. After doing this, I use cin>>n to read an integer into my int variable n.
#include <iostream>
using namespace std;
int main() {
int n;
char str[100];
cin.getline(str, 10, 'h');
cout<<str<<'-'<<endl;
cout<<"Enter a number:";
cin>>n;
cout<<n;
return 0;
}
假设我传递了以下输入
2 3 pl32
这是一个'\ n',后跟"2 3 pl32".我希望getline读取字符串"\ n2 3 pl"
,然后cin读取整数32.但这不是发生的情况.
which is a '\n' followed by "2 3 pl32".
I expect getline to read the string "\n2 3 pl"
and then cin to read the integer 32. But that's isn't what happened.
实际输出显示cin读取了垃圾值:
The actual output showed that the cin read garbage value:
2 3 pl-
Enter a number:0
好的,我现在明白了.Getline设置了 failbit
,这就是导致此问题的原因.问题解决了.
Ok, so I get it now. Getline set the failbit
, that's what caused the issue. Problem solved.
推荐答案
问题是 getline
找不到其定界符,并且已在 cin
中设置了故障位标志.您必须清除该标志才能在流上再次读取:
The problem is that getline
has not found its delimiter, and has set the failbit flag in cin
. You must clear the flag to read again on the stream:
...
cin.getline(str, 10, 'h');
cin.clear(); # reset a possible error condition
cout<<str<<'-'<<endl;
cout<<"Enter a number:";
cin>>n;
...
这篇关于使用getline后如何使cin工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!