getline(cin,aString)接收输入没有另一个输入 [英] getline(cin, aString) receiving input without another enter

查看:186
本文介绍了getline(cin,aString)接收输入没有另一个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示:

string aString;
cin >> aString;
cout << "This is what cin gets:" << aString << endl;
getline(cin, aString);
cout << "This is what getline(cin, <string>) gets:" << aString << endl;

每次运行时,我都会输入12,12 。

Each time I ran it, I give inputs like, "12", I get "12" and "".

我想知道为什么getline会在没有用户输入的情况下收到。

I am wondering why getline would received without user input.

像12 24,cin会得到12,getline应该得到其余的。 (另外,如果一个人可以回答,两者之间的空间被视为结束为cin,所以为什么它传递给getline?)

I can understand when I enter something like "12 24", cin will get "12", and getline should get the rest. (Also, if one could answer, the space in between is treated as an end for cin, so why is it passed on to getline?)

刚开始在字符串对C ++,所以请不要使它太难。谢谢。

Just starting out on string on C++ so please don't make it too hard. Thanks you.

推荐答案

当你将标准流提取与getline混合时,有时会有getline返回空字符串。这样做的原因是,如果你用>>读取输入,用户输入的换行字符表示它们已完成,不会从输入流中删除。因此,当你调用getline时,函数将读取剩余的换行符,并交回空字符串。

When you mix standard stream extraction with getline, you will sometimes have getline return the empty string. The reason for this is that if you read input with >>, the newline character entered by the user to signal that they're done is not removed from the input stream. Consequently, when you call getline, the function will read the leftover newline character and hand back the empty string.

要解决这个问题,要么始终使用getline作为输入,在读取之后使用ws流操纵器来提取额外的空白空间:

To fix this, either consistently use getline for your input, or use the ws stream manipulator to extract extra white space after a read:

cin >> value >> ws;

这将占用换行符,修复问题。

This will eat up the newline, fixing the problem.

希望这有助于!

这篇关于getline(cin,aString)接收输入没有另一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆