Using cin.get() to discard unwanted characters from the input stream in c++

六月ゝ 毕业季﹏ 提交于 2019-12-24 17:04:20

问题


I am working on an assignment for my C++ class. The following code is given. The directions explain to enter a six character string and observe the results. When I do this, the second user prompt is passed over and the program ends. I am pretty certain the reason for this is that the first cin.getline() is leaving the extra character(s) in the input stream which is messing up the second cin.getline() occurrence. I am to use cin.get, a loop, or both to prevent the extra string characters from interfering with the second cin.getline() function.

Any tips?

#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:


You are right. The newline character stays in the input buffer after the first input.

After the first read try to insert:

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

or better still:

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

You will have to #include <limits> header for this.

EDIT: Although using std::string would be much better, following modified code works:

#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;
}


来源:https://stackoverflow.com/questions/22188867/using-cin-get-to-discard-unwanted-characters-from-the-input-stream-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!