令人困惑的cin.get()语法

时间:2015-06-07 06:32:54

标签: c++ get delimiter

我读了一本书,提到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;
}

然后我在终端输入“迈阿密是一个城市(回车)”,得到以下结果:

Mi
0
not ignored: 
ignored: 
-1
0

我几点都没有意义。我没有输入'EOF',但是该字符的值为'-1'。我猜它可能是第二个cin.get(数组,10,'a');得到一个空行,它只是将其视为'EOF'?我对吗?如果是这样,那么“忽略”之后没有其他字符是有意义的。但如果是这样,为什么最后一个语句打印出'0'?谢谢!

1 个答案:

答案 0 :(得分:0)

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

  

如果未提取任何字符,请致电setstate(failbit)。在任何情况下,如果count>0,则空字符(CharT())存储在数组的下一个连续位置。

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

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;
}
相关问题