我正在为我的 C++ 类(class)做作业。给出以下代码。说明解释了如何输入六个字符串并观察结果。当我这样做时,第二个用户提示将被忽略并且程序结束。我很确定这样做的原因是第一个 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;
}
关于c++ - 在 C++ 中使用 cin.get() 丢弃输入流中不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22188867/