本文介绍了在C ++中使用cin.get()丢弃输入流中不需要的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的C ++类分配作业。给出以下代码。指导说明输入六个字符串并观察结果。当我这样做时,第二个用户提示就会通过,程序结束。我可以肯定的原因是,第一个cin.getline()在输入流中留下了多余的字符,这使第二个cin.getline()发生混乱。我将使用cin.get,循环或同时使用两者,以防止多余的字符串字符干扰第二个cin.getline()函数。

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.

有什么提示吗?

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


推荐答案

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

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

或更妙的是:

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

您将必须 #include< limits>

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

编辑:
尽管使用std :: string会更好,但修改后的代码可以工作:

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

这篇关于在C ++中使用cin.get()丢弃输入流中不需要的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:57