简体   繁体   English

istream :: ignore和getline()混淆

[英]istream::ignore and getline() confusion

I am helping someone with C++ input even though I don't know C++ myself. 尽管我自己不了解C ++,但我正在用C ++输入帮助某人。 Here's a short example: 这是一个简短的示例:

#include <iostream>
#include <string>

using namespace std;

int main() {
    int i;
    string s;

    cout << "enter i:\n";
    cin >> i;
    cout << "enter s:\n";
    getline(cin, s);
    //cin.ignore(100, '\n');
    cout << "i: " << i << ", s: " << s << "\n";
}

As expected, the getline() call will not prompt the user for input because it will simply swallow the trailing \\n after the cin >> i call and return immediately. 正如预期的那样, getline()调用不会提示用户输入,因为它只会在cin >> i调用之后吞下尾随\\n并立即返回。 What I find odd is that if you uncomment the cin.ignore() call, the getline() call will prompt the user for input (even though nothing will be saved into s ). 我发现奇怪的是,如果取消注释cin.ignore()调用,则getline()调用提示用户输入(即使不会将任何内容保存到s )。 Could someone explain why? 有人可以解释为什么吗? In my view, the line in question should not change the behaviour at all. 我认为,所讨论的行根本不应更改行为。

What I find odd is that if you uncomment the cin.ignore() call, the getline() call will prompt the user for input 我发现奇怪的是,如果取消注释cin.ignore()调用,则getline()调用将提示用户输入

No, it won't. 不,不会。 It's the ignore statement that's prompting the user. 提示用户的是ignore语句。 As you have it, it's doing essentially the same thing as getline does, except that it will only read up to 100 characters, and it just throws them away. 有了它,它实际上与getline所做的事情相同,只是它最多只能读取100个字符,并且只会丢弃它们。

Well, no. 好吧,不。 It is not the case that " getline() will prompt the user for input". 并非“ getline()会提示用户输入”的情况。 Clearly the ignore statement comes after the getline() one. 显然, ignore语句位于getline() 之后

What happens is that the ignore() statement simply blocks until it fulfils its task, ie gobble up 100 characters or a newline, whichever comes first (but mind the input buffering). 发生的事情是, ignore()语句只是阻塞直到它完成其任务,即吞掉100个字符或换行符(以先到者为准)(但要注意输入缓冲)。

As a general, though not directly related, piece of advice: don't mix token extraction ( >> ) and getline() , for exactly this problem concerning newlines. 通常,尽管没有直接关系,但建议:不要将令牌提取( >> )和getline() ,因为这个问题涉及换行符。 Much better to just stick to one thing; 只坚持一件事更好; preferably line reading so you can deal with errors and repeat the prompt. 最好是在线阅读,以便您可以处理错误并重复提示。 Also consider any unchecked read operation ( >> , getline() , or istream::read() ) a programming error; 还要考虑任何未经检查的读取操作( >>getline()istream::read() )是编程错误; there should be conditionals surrounding all of those. 所有这些都应该有条件。

It's not the getline call that's waiting for input, it's the ignore one that is waiting for things to ignore. 等待输入的不是getline调用,而是等待ignore的“ ignore调用。

Put the ignore call before the getline . ignore调用放在getline之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM