在C ++中使用getline() [英] Using getline() in C++
问题描述
我有一个问题使用getline方法来获取一个消息,用户类型,我使用像:
I have a problem using getline method to get a message that user types, I'm using something like:
string messageVar;
cout << "Type your message: ";
getline(cin, messageVar);
但是,它不是停止获取输出值,这有什么问题?
However, it's not stopping to get the output value, what's wrong with this?
推荐答案
如果你在 cin>> something
,您需要从中间的缓冲区中刷新换行符。您可以使用 cin.ignore()
If you're using getline after cin >> something
, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore()
这样做:
string messageVar;
cout << "Type your message: ";
cin.ignore();
getline(cin, messageVar);
这是因为>>
操作符在输入缓冲区中留下换行符 \\\
。这可能会成为一个问题,当你做无格式的输入,如
getline()
,读取输入直到找到换行符。这会发生,它会立即停止读取,因为 \\\
在你以前的操作中被挂在那里。
This happens because the >>
operator leaves a newline \n
character in the input buffer. This may become a problem when you do unformatted input, like getline()
, which reads input until a newline character is found. This happening, it will stop reading immediatly, because of that \n
that was left hanging there in your previous operation.
这篇关于在C ++中使用getline()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!