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

标签 c++ cin

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

相关文章:

c++ - 将特征矩阵转换为三元组形式 C++

c++ - std::sort() 中的程序有时会崩溃,无法重现

c++ - while 循环不能有两个 cin 语句吗?

C++ Wininet 自定义 http header

c++ - 在 C 或 C++ 中将字母数字字符串 abcd1234 增加到 abcd2000

c++ - IShellFolder::ParseDisplayName 以获取控制面板项的 ITEMIDLIST

c++ - OSX C++ Xcode : Pasting long input into console gives upside down question marks

c++ - 指向 C++ 中的结构的指针 - 从控制台读取?

c++ - Cin 被跳过,cin.ignore 不工作

c++ - 我如何在不中断行的情况下在 C++ 控制台中写入文本