简体   繁体   English

cin.ignore如何与cin和getline一起使用?

[英]How does cin.ignore work with cin and getline?

Here, there are two cins and to my understanding, each one leaves '\\n' in the buffer because they skip whitespace. 在这里,有两个cin,据我所知,每个cin都会在缓冲区中保留'\\ n',因为它们会跳过空格。

Cin.ignore only skips one character by default so one of the '\\n' is taken out. Cin.ignore默认情况下仅跳过一个字符,因此将'\\ n'之一取出。 However, there is still one more '\\n' in the buffer, so I would expect the getline to see the '\\n' and getline to skip. 但是,缓冲区中仍然还有一个'\\ n',所以我希望getline看到'\\ n',而getline会跳过。

However, when I run this code, I am able to type into string3. 但是,当我运行此代码时,我可以键入string3。 Where am I going wrong? 我要去哪里错了?

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string string1, string2, string3;
  cout << "String1: ";
  cin >> string1;

  cout << "String2: ";
  cin >> string2; 

  cin.ignore();

  cout << "String3: ";
  getline(cin, string3);

  return 0;
}

cin >> string2 looks for the beginning of the next word, and skips over the newline that was left in the buffer after cin >> string1 . cin >> string2寻找下一个单词的开头,并跳过cin >> string1之后留在缓冲区中的换行符。 So at this point ,only the second newline is still in the buffer, and cin.ignore() skips past it. 因此,在这一点上,只有第二个换行符仍在缓冲区中,并且cin.ignore()跳过了它。

More detailed, if you type: 如果输入以下内容,则更详细:

line1
line2
line3

The buffer contains: 缓冲区包含:

line1\nline2\nline3\n
^

The ^ shows the current position in the buffer. ^显示缓冲区中的当前位置。 At the beginning, it's at the beginning of the buffer. 在开始处,它是在缓冲区的开始处。 After you do cin >> string1 , it looks like: 完成cin >> string1 ,它看起来像:

line1\nline2\nline3\n
     ^

When you do cin >> string2 , it finds the beginning of the next word (the next l character), and after it's done the buffer looks like: 当您执行cin >> string2 ,它将找到下一个单词(下一个l字符)的开头,并且在完成后,缓冲区看起来像:

line1\nline2\nline3\n
            ^

Then cin.ignore() skips past the next newline, so it looks like: 然后cin.ignore()跳过下一个换行符,因此看起来像:

line1\nline2\nline3\n
              ^

And now when you call getline() , it reads the line with line3 . 现在,当您调用getline() ,它将读取带有line3的行。

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

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