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

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

本文关键字:输入流 字符 不需要 c++ cin get      更新时间:2023-10-16

我正在为我的C++类进行赋值。给出了以下代码。说明说明输入一个六个字符的字符串并观察结果。当我这样做时,第二个用户提示被传递,程序结束。我很确定这是因为第一个cin.getline()在输入流中留下了额外的字符,这会打乱第二个cin.get()的出现。我将使用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] = '';
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] = '';
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}