本文介绍了使用cin两次的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是代码:

string str;
cin>>str;
cout<<"first input:"<<str<<endl;
getline(cin, str);
cout<<"line input:"<<str<<endl;

在花费一些时间之后,我意识到在第一次调用cin >> str之后, ,似乎'\\\
'仍然存储在cin(使用cin.peek()检查),它立即结束getline。解决方案将在第一次使用和第二次使用之间添加一行:
cin.ignore(numeric_limits :: max(),'\\\
');

After spending some time on it, I realized after the first call "cin>>str", it seems '\n' is still stored in cin (using cin.peek() to check), which ends getline immediately. The solution will be adding one more line between the first usage and the second one:cin.ignore(numeric_limits::max(), '\n');

但是,我还是不明白,为什么在第一次调用后'\\\
'什么是istream&操作符>>真的吗?

However, I still don't understand, why is '\n' left there after the first call? What does istream& operator>> really do?

推荐答案

良好的说明,解释了你遇到这个问题的一些原因,主要是由于输入类型的行为和你正在混合它们

Good writeup that explains some of the reasons why you are running into this issue, primarily due to the behavior of the input types and that you are mixing them

这篇关于使用cin两次的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

查看更多