亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我們要在讀取輸入后調用cin.CLEAR()和cin.IGNORE()?

為什么我們要在讀取輸入后調用cin.CLEAR()和cin.IGNORE()?

C++
墨色風雨 2019-06-16 13:39:45
谷歌代碼大學C+教程以前有這樣的代碼:// Description: Illustrate the use of cin to get input// and how to recover from errors.#include <iostream>using namespace std;int main(){   int input_var = 0;   // Enter the do while loop and stay there until either   // a non-numeric is entered, or -1 is entered.  Note that   // cin will accept any integer, 4, 40, 400, etc.   do {     cout << "Enter a number (-1 = quit): ";     // The following line accepts input from the keyboard into     // variable input_var.     // cin returns false if an input operation fails, that is, if     // something other than an int (the type of input_var) is entered.     if (!(cin >> input_var)) {       cout << "Please enter numbers only." << endl;       cin.clear();       cin.ignore(10000,'\n');     }     if (input_var != -1) {       cout << "You entered " << input_var << endl;     }   }   while (input_var != -1);   cout << "All done." << endl;   return 0;}…的意義是什么?cin.clear()和cin.ignore()?為什么10000和\n必要的參數?為什么我們要在讀取輸入后調用cin.CLEAR()和cin.IGNORE()?
查看完整描述

3 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

這個cin.clear()清除錯誤標志。cin(這樣以后的I/O操作將正確工作),然后cin.ignore(10000, '\n')跳到下一個換行符(忽略與非數字相同的行上的任何其他內容,這樣就不會導致另一個解析失敗)。它只會跳過10000個字符,所以代碼假設用戶不會放一個非常長、無效的行。


查看完整回答
反對 回復 2019-06-16
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

輸入

if (!(cin >> input_var))

語句,如果在從CIN獲取輸入時發生錯誤。如果發生錯誤,則設置錯誤標志,以后獲取輸入的嘗試將失敗。所以你需要

cin.clear();

以消除錯誤標志。而且,失敗的輸入將位于我假設的某種緩沖區中。當您再次嘗試獲取輸入時,它將在緩沖區中讀取相同的輸入,然后再次失敗。所以你需要

cin.ignore(10000,'\n');

它從緩沖區中取出10000個字符,但如果遇到換行符(\n),則停止。10000只是一個普通的大值。


查看完整回答
反對 回復 2019-06-16
  • 3 回答
  • 0 關注
  • 856 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號