02.26 C++|文本輸入與緩衝以及合法性檢查

1 輸入、緩衝

When the user enters input in response to an extraction operation, that data is placed in a buffer inside of std::cin. A buffer

(also called a data buffer) is simply a piece of memory set aside for storing data temporarily while it’s moved from one place to another. In this case, the buffer is used to hold user input while it’s waiting to be extracted to variables.

當用戶輸入輸入以響應提取操作時,該數據將放在std::cin內的緩衝區中。緩衝區(也稱為數據緩衝區)只是一塊內存,當數據從一個地方移動到另一個地方時,它被臨時存儲起來。在這種情況下,緩衝區用於在等待提取到變量時保存用戶輸入。

(文件的輸入、輸出也會有文件輸入、輸出緩衝區。)

When the extraction operator is used, the following procedure happens:

使用提取運算符時,將執行以下過程:

If there is data already in the input buffer, that data is used for extraction.

如果輸入緩衝區中已有數據,則該數據將用於提取。

If the input buffer contains no data, the user is asked to input data for extraction (this is the case most of the time). When the user hits enter, a ‘\\n’ character will be placed in the input buffer.

如果輸入緩衝區不包含數據,則要求用戶輸入數據進行提取(大多數情況下都是這樣)。當用戶點擊enter時,一個'\\n'字符將被放入輸入緩衝區。

operator>> extracts as much data from the input buffer as it can into the variable (ignoring any leading whitespace characters, such as spaces, tabs, or ‘\\n’).

operator>>從輸入緩衝區中提取儘可能多的數據到變量中(忽略任何前導空格字符,如空格、製表符或'\\n')。

Any data that can not be extracted is left in the input buffer for the next extraction.

無法提取的任何數據都會留在輸入緩衝區中,以便下次提取。

C++|文本輸入與緩衝以及合法性檢查

如以下簡單語句:

<code>char ch;cout</<code>

當輸入a,數據存入緩衝區,未回車時,等待用戶繼續,只有當用記回車時,cin.get())開始從緩衝區讀取數據,直到'\\n'。

2 合法性檢查

The process of checking whether user input conforms to what the program is expecting is called input validation.

檢查用戶輸入是否符合程序期望的過程稱為輸入驗證。

We can generally separate input text errors into four types:

我們通常可以將輸入文本錯誤分為四種類型:

Input extraction succeeds but the input is meaningless to the program (e.g. entering ‘k’ as your mathematical operator).

輸入提取成功,但輸入對程序沒有意義(例如,輸入“k”作為數學運算符)。

(需要具體內容匹配檢查;)

Input extraction succeeds but the user enters additional input (e.g. entering ‘*q hello’ as your mathematical operator).

輸入提取成功,但用戶輸入了其他輸入(例如,輸入“*q hello”作為數學運算符)。

(長度匹配檢查或緩衝區清除;)

Input extraction fails (e.g. trying to enter ‘q’ into a numeric input.the text is left in the buffer, and std::cin goes into “failure mode”.)

輸入提取失敗(例如,試圖在數字輸入中輸入“q”)。

(類型匹配檢查,輸入錯誤信息清查,緩衝區清除;)

Input extraction succeeds but the user overflows a numeric value.

輸入提取成功,但用戶溢出了一個數值。

(溢出檢查;)

以下是上述內容的一個綜合實例:

<code>#include <iostream>) double getDouble(){    while (true) // Loop until user enters a valid input    {        std::cout << "Enter a double value: ";        double x;        std::cin >> x;         // Check for failed extraction        if (std::cin.fail()) // has a previous extraction failed?        {            // yep, so let's handle the failure            std::cin.clear(); // put us back in 'normal' operation mode            std::cin.ignore(32767,'\\n'); // and remove the bad input            std::cout << "Oops, that input is invalid.  Please try again.\\n";        }        else        {            std::cin.ignore(32767,'\\n'); // remove any extraneous input             // the user can't enter a meaningless double value, so we don't need to worry about validating that            return x;        }    }} char getOperator(){    while (true) // Loop until user enters a valid input    {        std::cout << "Enter one of the following: +, -, *, or /: ";        char op;        std::cin >> op;         // Chars can accept any single input character, so no need to check for an invalid extraction here         std::cin.ignore(32767,'\\n'); // remove any extraneous input         // Check whether the user entered meaningful input        if (op == '+' || op == '-' || op == '*' || op == '/')                return op; // return it to the caller        else // otherwise tell the user what went wrong            std::cout << "Oops, that input is invalid.  Please try again.\\n";    } // and try again} void printResult(double x, char op, double y){    if (op == '+')        std::cout << x << " + " << y << " is " << x + y << '\\n';    else if (op == '-')        std::cout << x << " - " << y << " is " << x - y << '\\n';    else if (op == '*')        std::cout << x << " * " << y << " is " << x * y << '\\n';    else if (op == '/')        std::cout << x << " / " << y << " is " << x / y << '\\n';    else // Being robust means handling unexpected parameters as well, even though getOperator() guarantees op is valid in this particular program        std::cout << "Something went wrong: printResult() got an invalid operator."; } int main(){    double x = getDouble();    char op = getOperator();    double y = getDouble();     printResult(x, op, y);     return 0;}/<iostream>/<code>

總結一下:

As you write your programs, consider how users will misuse your program, especially around text input. For each point of text input, consider:

在編寫程序時,請考慮用戶如何濫用程序,尤其是在文本輸入方面。對於文本輸入的每個點,請考慮:

Could extraction fail?

提取會失敗嗎?

Could the user enter more input than expected?

用戶能否輸入比預期更多的輸入?

Could the user enter meaningless input?

用戶是否可以輸入無意義的輸入?

Could the user overflow an input?

用戶是否可以使輸入溢出?

You can use if statements and boolean logic to test whether input is expected and meaningful.

您可以使用if語句和布爾邏輯來測試輸入是否是預期的和有意義的。

3 輸入輸出相關函數總結


C++|文本輸入與緩衝以及合法性檢查

4 文件輸入輸出相關函數總結


C++|文本輸入與緩衝以及合法性檢查


-End-


分享到:


相關文章: