到目前为止,我已经尝试制作一个do…while循环,其中它会问两个问题。一个是多少英里,另一个是包裹的重量。如果英里数等于0或更小,它应该输出一个错误,然后重新提问。一旦验证,它应该以相同的要求进入重量问题,如果重量无效,它应该只重复重量问题,因为里程问题已经有效。
这是我目前拥有的代码:
int miles = 0;
int choice = 0;
double weight = 0.0;
do
{
cout << "Enter the number of miles as a whole number: ";
cin >> miles;
if (miles > 0)
{
cout << "Enter the weight of the package in pounds: ";
cin >> weight;
if (weight > 0 && weight < 10)
{
cout << "etc etc etc";
}
else
{
cout << "ntError: Weight must be greater than zero and less than 10 pounds!n" << endl;
}
}
else
{
cout << "ntError: Miles must be greater than zero!n" << endl;
}
cout << "Enter 1 to continue or 0 to quit: ";
cin >> choice;
cout << endl;
}
while (choice != 0);
cout << "nGood-bye!n";
return 0;
您需要额外的循环来读取cin
,直到输入有效为止。在对某个值执行范围检查之前,您需要确保cin
甚至能够成功读取该值。
我建议在单独的功能中进行读取+验证,例如:
#include <iostream>
#include <limits>
template<typename T>
T prompt(const char *msg, T maxValue = std::numeric_limits<T>::max())
{
T value;
do
{
cout << msg << ": ";
if (!(cin >> value))
{
cout << "ntError: Invalid input!n" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
else if (value < 0)
{
cout << "ntError: Value must be greater than 0!n" << endl;
}
else if (value >= maxValue)
{
cout << "ntError: Value must be less than " << maxValue << "!n" << endl;
}
else
break;
}
while (true);
return value;
}
...
int miles;
double weight;
int choice;
do
{
miles = prompt<int>("Enter the number of miles as a whole number");
weight = prompt<double>("Enter the weight of the package in pounds", 10.0);
choice = prompt<int>("Enter 1 to continue or 0 to quit", 2);
cout << endl;
}
while (choice != 0);
cout << "nGood-bye!n";
您可以使用多个while循环,每个输入一个。
int miles = 0;
double weight = 0.0;
bool correct = false;
while (!correct)
{
cout << "Enter the number of miles as a whole number: " << std::endl;
bool success = cin >> miles;
if (!success || miles < 0) {
cout << "Invalid miles value -- must be nonnegative." << std::endl;
}
else {
correct = true;
}
}
correct = false;
while (!correct)
{
cout << "Enter the weight in pounds: " << std::endl;
bool success = cin >> weight;
if (!success || weight < 0 || weight > 10) {
cout << "Invalid weight value -- must be between 0 and 10." << std::endl;
}
else {
correct = true;
}
}
// do calculation
cout << "nGood-bye!n";
return 0;