cin.get() 的混乱语法

confusing syntax of cin.get()

我看过一本书提到 cin.get() 会在输入流中保留定界符,因此,使用相同定界符的后续连续调用的结果是一个空行。所以我写了下面的代码来测试这个属性和其他

#include <iostream>
using namespace std;

int main()
{
  char array[10];
  int character;
  cin.get(array, 10, 'a');
  cout << endl << array << endl;
  cout << cin.eof() << endl;
  cin.get(array, 10, 'a');
  cout << "not ignored: " << array << endl;

  cin.ignore();
  cin.get(array, 10,'a');
  cout << "ignored: " << array << endl;

  while((character=cin.get())!=EOF){}
  cout << character << endl;
  cout << cin.eof() << endl;
}

然后我在终端输入"Miami is a city(Enter)",得到如下结果:

Mi
0
not ignored: 
ignored: 
-1
0

有几点我没看懂。我没有输入“EOF”,但该字符的值为“-1”。我猜可能是第二个 cin.get(array, 10, 'a');得到一个空行,它只是将其视为“EOF”?我对吗?如果是这样,"ignored:" 后面没有其他字符是有道理的。但如果是这样,为什么最后一条语句打印出'0'?谢谢!

来自http://en.cppreference.com/w/cpp/io/basic_istream/get

If no characters were extracted, calls setstate(failbit). In any case, if count>0, a null character (CharT() is stored in the next successive location of the array.

因为在第二次调用中没有提取任何字符

cin.get(array, 10, 'a');

failbit 已设置。您必须先清除状态,然后才能从字符串中读取更多字符。

工作代码:

#include <iostream>
using namespace std;

int main()
{
  char array[10];
  int character;
  cin.get(array, 10, 'a');
  cout << endl << array << endl;
  cout << cin.eof() << endl;

  cin.get(array, 10, 'a');
  // failbit is set since no characters were extracted in the
  // above call.

  cout << "not ignored: " << array << endl;

  // Clear the stream
  cin.clear();

  cin.ignore();
  cin.get(array, 10,'a');
  cout << "ignored: " << array << endl;

  while((character=cin.get())!=EOF){}
  cout << character << endl;
  cout << cin.eof() << endl;
}