C++ 中 cin.ignore() 的作用是什麼?


cin.ignore() 函式用於忽略或清除輸入緩衝區中的一個或多個字元。

為了瞭解 ignore() 的工作原理,我們必須先看看一個問題,而解決該問題的方案就是使用 ignore() 函式。問題如下所示。

有時我們需要清除不需要的緩衝區,以便在獲取下一個輸入時,它儲存到所需的容器中,而不是儲存到先前變數的緩衝區中。例如,在輸入 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 語句,但只獲取了數字。當我們按下 Enter 鍵時,它跳過了 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

更新於: 2023-09-02

64K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.