如何在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP