使用getline后如何使cin工作?

编程入门 行业动态 更新时间:2024-10-20 05:25:50
本文介绍了使用getline后如何使cin工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我使用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工作?

本文发布于:2023-11-25 15:27:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630296.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作   getline   cin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!