使用cin.get()从c ++中的输入流中丢弃不需要的字符

时间:2014-03-05 04:52:38

标签: c++ cin

我正在为我的C ++课做作业。给出以下代码。方向说明输入六个字符串并观察结果。当我这样做时,第二个用户提示被传递,程序结束。我很确定这是因为第一个cin.getline()在输入流中留下额外的字符,这会弄乱第二个cin.getline()。我将使用cin.get,循环或两者来防止额外的字符串字符干扰第二个cin.getline()函数。

任何提示?

#include <iostream>
using namespace std;
int main()
{
   char buffer[6];
   cout << "Enter five character string: ";
   cin.getline(buffer, 6);
   cout << endl << endl;
   cout << "The string you entered was " << buffer << endl;
   cout << "Enter another five character string: ";
   cin.getline(buffer, 6);
   cout << endl << endl;
   cout << "The string you entered was " << buffer << endl;
   return 0;
}

1 个答案:

答案 0 :(得分:4)

你是对的。第一次输入后,换行符将保留在输入缓冲区中。

第一次阅读后尝试插入:

cin.ignore(); // to ignore the newline character

或更好:

//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

您需要#include <limits>标题。

编辑: 虽然使用std :: string会好得多,但是修改后的代码可以工作:

#include <iostream>
#include <limits>

using namespace std;
int main()
{
   char buffer[6];
   cout << "Enter five character string: ";
   for (int i = 0; i < 5; i++)
      cin.get(buffer[i]);
   buffer[5] = '\0';
   cin.ignore(numeric_limits<streamsize>::max(), '\n');

   cout << endl << endl;
   cout << "The string you entered was " << buffer << endl;

   cout << "Enter another five character string: ";
   for (int i = 0; i < 5; i++)
      cin.get(buffer[i]);
   buffer[5] = '\0';
   cin.ignore(numeric_limits<streamsize>::max(), '\n');

   cout << endl << endl;
   cout << "The string you entered was " << buffer << endl;
   return 0;
}