[英]How to validate input in a do...while loop and then re-ask question if necessary?
到目前為止,我已經嘗試做一個 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 << "\n\tError: Weight must be greater than zero and less than 10 pounds!\n" << endl;
}
}
else
{
cout << "\n\tError: 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;
您可以使用多個 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;
您需要額外的循環才能從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 << "\n\tError: Invalid input!\n" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else if (value < 0)
{
cout << "\n\tError: Value must be greater than 0!\n" << endl;
}
else if (value >= maxValue)
{
cout << "\n\tError: 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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.