优雅地检查用户输入的错误
Check user input for errors elegantly
我的程序等待用户输入,并在适当的时候处理它。我需要检查用户输入,以确保它满足某些标准,如果它不满足所有这些标准,它将被拒绝。
伪代码类似于:
if (fulfills_condition_1)
{
if (fulfills_condition_2)
{
if (fulfills_condition_3)
{
/*process message*/
}
else
cout << error_message_3; //where error_message_1 is a string detailing error
}
else
cout << error_message_2; //where error_message_2 is a string detailing error
}
else
cout << error_message_1; //where error_message_3 is a string detailing error
这些条件的数量可能会增加,我想知道是否有一种更简洁的方式来表示这一点,使用开关或类似的东西,而不是大量的级联if
语句。
我知道有可能使用
if (fulfills_condition_1 && fulfills_condition_2 && fulfills_condition_3)
/*process message*/
else
error_message; //"this message is not formatted properly"
,但这没有第一个有用,并且没有说明问题在哪里。
条件可以大致按重要性递增排列,即检查condition_1
比检查condition_3
更重要,因此if
语句确实有效-但是是否有更好的方法来实现这一点?
if (!fulfills_condition_1) throw BadInput(error_message_1);
if (!fulfills_condition_2) throw BadInput(error_message_2);
if (!fulfills_condition_3) throw BadInput(error_message_3);
/* process message */
那么您的异常处理程序可以报告错误消息,并在适当的时候重试或中止。
如果您是级联的if
s困扰,您可以选择以下之一:
使用boolean:
bool is_valid = true;
string error = "";
if (!condition_one) {
error = "my error";
is_valid = false;
}
if (is_valid && !condition_two) {
...
}
...
if (!is_valid) {
cout << error;
} else {
// Do something with valid input
}
使用例外:try {
if (!condition_one) {
throw runtime_error("my error");
}
if (!condition_two) {
...
}
...
} catch (...) {
// Handle your exception here
}
我建议你可以使用"提前返回"技术:
if (!fulfills_condition_1)
// error msg here.
return;
// fulfills_condition1 holds here.
if (!fulfills_condition_2)
// error msg here.
return;
// Both conditon1 and condition2 hold here.
if (!fulfills_condition_3)
// error msg here.
return.
如果要在一些地方重用它,我会创建一个DSL:
Validator inputType1Validator =
Validator.should(fulfill_condition_1, error_message_1)
.and(fulfill_condition_2, error_message_2)
.and(fulfill_condition_3, error_message_3)
inputType1Validator.check(input);
相关文章:
- 堆栈中大小变量输入错误 (C++)
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 如何从标准输入中检测格式化输入错误?
- 如何在没有打印语句的情况下报告用户输入错误
- 用户输入错误
- 按下Enter时如何输入错误消息,但没有给出任何答案
- 在我的IF-ELSE循环中输入错误
- C++ 输入错误
- C++ 函数输入错误
- 使用ifstreamwhile循环,如何显示输入错误并在下一行继续
- switch 语句中的输入错误 如何循环回第一种情况?C++
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 如果我输入错误的 dos 命令,shellexecute 会给出正确的结果
- C++输入错误的数组
- scanf和多个输入错误
- C++输入浮点而不是整数时的输入错误
- 使用字符串流和if-else语句时发生字符串输入错误
- 当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
- setw() 在包含 UTF-8 多字节字符/码位的字符串上输入错误的输出
- c++中的getline输入错误