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>\tchar ch;
\tcout<\twhile((ch=cin.get())!='\\n')
\t\tcout.put(ch);/<code>

当输入a,数据存入缓冲区,未回车时,等待用户继续,只有当用记回车时,cin.get())开始从缓冲区读取数据,直到'\\n'。

C++|文本输入与缓冲以及合法性检查

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-


分享到:


相關文章: