簡體   English   中英

C++ 中的用戶輸入驗證測試

[英]User input validation test in C++

我在“使用 C++ 的 Bjarne Stroustrup 編程原則和實踐”的第 5 章中的練習 9 中遇到了問題。

這一章是關於錯誤的,練習說“如果結果不能表示為int,則修改練習8中的程序以寫出錯誤”。

我嘗試使用各種變體

if (!cin)
error("Input is not an integer"); 

但是,我遇到的問題是,如果我讀入的不是整數的內容,它要么顯示所有錯誤,要么僅顯示“您想對比輸入的值求和的值多”錯誤。

這是我在嘗試添加用戶輸入錯誤之前來自練習 8 的完整代碼:

#include <iostream>
#include "../../std_lib_facilities.h"


int main()
{
    try {
        int size = 0;
        int numbers = 0;
        int sum = 0;
        vector<int>values;

        cout << "Please enter how many numbers you want to sum\n";
        cin >> size;

        if (size < 1)
            error("you have to enter at least one value!");


        cout << "enter some integers and then | to sum them\n";

        while (cin >> numbers)
            values.push_back(numbers);

         if (values.size() < size)
            error(" You wanted to sum more values than you entered. ");

        cout << "the sum of the first " << size << " numbers ( ";

        for (int i = 0; i < size; ++i) {
            sum += values[i];
            cout << values[i] << " ";
        }
        cout << ") is : " << sum << "\n";

        return 0;
    }
    catch (exception& e) {
        cerr << "Error: " << e.what() << "\n";
        keep_window_open();
        return 1;
    }
    catch (...) {
        cerr << "Oops: Unknown exception!\n";
        keep_window_open();
        return 2;
    }
}

我認為您可以使用cin.fail()方法來檢測錯誤的輸入。

例如

int numbers = 0;
cin >> numbers;
if (cin.fail())
{
   /* run when the input is not integer. */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM