How to make cin work after using getline?

倖福魔咒の 提交于 2021-02-17 07:01:27

问题


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;
}

Suppose I pass the following input


2 3   pl32

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.

The actual output showed that the cin read garbage value:


2 3   pl-
Enter a number:0

Edit: Ok, so I get it now. Getline set the failbit , that's what caused the issue. Problem solved.


回答1:


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;
...


来源:https://stackoverflow.com/questions/56474039/how-to-make-cin-work-after-using-getline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!