首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Code::Blocks 下第一個 C++ 程序:異常處理與輸入驗證實例

     編輯:關於C++

完整代碼


#include <iostream>
#include <exception>
#include <string>

using namespace std;

class Test {
public:
    string name;
    long id;
    bool pass;

    void getUser() {
        pass = false;
        while (!pass) {
            try {
                pass = true;
                cout << "Input your id: " << endl;
                cin >> id;
                if (cin.fail()) {
                    throw new exception;
                }
                cout << "Input your name: " << endl;
                cin >> name;
                // 非異常處理寫法對比
                if (cin.fail()) {
                    pass = false;
                    cin.clear();
                    cout << "Your name is wrong, please input again!" << endl;
                    continue;
                }
            } catch (exception* e) {  // 必須捕獲指針,因拋出的是 new exception
                pass = false;
                cout << "Your inputing is wrong, please input again!" << endl;
                cin.clear();  // 關鍵:清除錯誤狀態,否則陷入死循環
                delete e;     // 釋放拋出的異常對象
            }
        }
    }

    void display() {
        cout << "This is my first class processed in linux!" << endl;
        cout << "my name is " << name << endl;
    }
};

int main() {
    Test* tt = new Test();
    tt->getUser();
    tt->display();
    delete tt;
    return 0;
}

關鍵知識點筆記

1. cin.fail() 檢測輸入失敗

  • 當輸入類型不匹配(如預期 int 卻輸入 "abc"),cin 進入失敗狀態,fail() 返回 true
  • 失敗狀態下,**後續所有輸出操作均無效**,必須調用 cin.clear() 重置狀態位

2. cin.clear() 的關鍵作用

  • 清除 failbit/badbit,恢復流為良好狀態
  • **不清除緩衝區內容**!殘留的非法字符仍在緩衝區,需配合 cin.ignore(numeric_limits<streamsize>::max(), '\n') 丟棄
  • 示例中未 ignore,若輸入 "abc",下次循環仍讀到 "abc" → 無限循環。建議補全:

cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

3. 捕獲 exception* 指針

  • 代碼拋出 throw new exception(指針),故捕獲必須用 catch (exception* e)
  • 捕獲後必須 delete e,否則內存洩漏
  • **現代 C++ 不推薦拋出指針**,應拋出值:throw std::runtime_error("msg"),捕獲用 catch (const std::exception& e)

4. 異常處理 vs 狀態檢查

示例中兩種寫法並存僅為教學對比,**實際項目中二選一**,輸入驗證首選狀態檢查。

改進版輸入驗證模板


template <typename T>
bool safe_input(T& out, const string& prompt) {
    while (true) {
        cout << prompt;
        if (cin >> out) return true;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input, try again.\n";
    }
}

// 使用
long id;
safe_input(id, "Input your id: ");
string name;
safe_input(name, "Input your name: ");

編譯環境說明

  • IDE:Code::Blocks (Linux/Windows 跨平台)
  • 編譯器:GCC (g++)
  • 標準:C++11 或更高(建議 -std=c++17)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方式代碼量控制流適用場景
try-catch較多非局部跳轉真正的異常情況(資源耗盡、邏輯錯誤)
cin.fail() + clear/ignore較少順序執行可預期的輸入格式錯誤