这是检查用户输入的好习惯吗?
Is this a good practice to check user input?
do {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
} while (!validName(name) && std::cout << "It is not a valid name" << std::endl);
如果名称无效,我会这样回复一行,这是一个好习惯吗?
在循环本身内进行检查和输出可能更清楚。您可以通过打破无限循环或继续一次性循环来完成此操作。例如:
do {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (!validName(name)) {
std::cout << "It is not a valid name" << std::endl;
continue;
}
} while (false);
或相反:
for ( ;; ) {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (validName(name))
break;
std::cout << "It is not a valid name" << std::endl;
}
我通常更喜欢第二种,因为它可以很容易地注入计数器,因此如果循环体失败超过一定次数,您可以进行一些其他类型的错误处理。
for (int attempt = 0; attempt < 3; ++attempt) {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (validName(name))
break;
std::cout << "It is not a valid name" << std::endl;
}
if (!validName(name)) {
std::cout << "Failed to get a valid name after 3 tries" << std::endl;
std::abort();
}
do {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
} while (!validName(name) && std::cout << "It is not a valid name" << std::endl);
如果名称无效,我会这样回复一行,这是一个好习惯吗?
在循环本身内进行检查和输出可能更清楚。您可以通过打破无限循环或继续一次性循环来完成此操作。例如:
do {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (!validName(name)) {
std::cout << "It is not a valid name" << std::endl;
continue;
}
} while (false);
或相反:
for ( ;; ) {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (validName(name))
break;
std::cout << "It is not a valid name" << std::endl;
}
我通常更喜欢第二种,因为它可以很容易地注入计数器,因此如果循环体失败超过一定次数,您可以进行一些其他类型的错误处理。
for (int attempt = 0; attempt < 3; ++attempt) {
std::cout << "Enter a valid name" << std::endl;
std::cin >> name;
if (validName(name))
break;
std::cout << "It is not a valid name" << std::endl;
}
if (!validName(name)) {
std::cout << "Failed to get a valid name after 3 tries" << std::endl;
std::abort();
}