如何在 C++ 中清空 cin 缓冲区?


在本节中,我们将了解如何在 C++ 中清空 cin 缓冲区。在进入讨论之前,让我们先了解一下 C++ 中的缓冲区是什么。

缓冲区是一个临时存储区域。所有标准 IO 设备都使用缓冲区来保存数据,并在它们工作时使用。在 C++ 中,流本质上也是缓冲区。当我们按下某个键时,它不会立即发送到程序。它们会被存储在缓冲区中。操作系统会将它们缓冲,直到程序获得分配的时间。

有时我们需要清除不需要的缓冲区,以便在下次获取输入时,它会存储到所需的容器中,而不是存储在先前变量的缓冲区中。例如,在输入 cin 语句后,我们需要输入一个字符数组或字符串。因此,我们需要清除输入缓冲区,否则它将占用先前变量的缓冲区。在第一个输入后按下“Enter”键,由于先前变量的缓冲区有空间容纳新数据,程序将跳过容器的后续输入。

示例

#include<iostream>
#include<vector>
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}

输出

Enter a number and a string:
8
You have entered:
8

有两个用于整数和字符串的 cin 语句,但只获取了数字。当我们按下回车键时,它会跳过 getLine() 函数而不获取任何输入。有时它可以获取输入,但它在整数变量的缓冲区内,因此我们无法看到字符串作为输出。

现在,为了解决这个问题,我们将使用 cin.ignore() 函数。此函数用于忽略最多指定范围内的输入。如果我们这样写语句

cin.ignore(numeric_limits::max(), ‘\n’)

那么它会忽略包括换行符在内的输入。

示例

#include<iostream>
#include<ios> //used to get stream size
#include<limits> //used to get numeric limits
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer before taking new line
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}

输出

Enter a number and a string:
4
Hello World
You have entered:
4
Hello World

更新于: 2019-07-30

2K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.