繁体   English   中英

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

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

我正在为我的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;
}

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

第一次阅读后,尝试插入:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM