如何将输入验证包含在此代码中

How do I incorporate input validation in this code?

本文关键字:代码 包含 验证 输入      更新时间:2023-10-16

我试图在这个程序中实现输入验证,但结果总是出错。我尝试使用另一个while语句,但它不起作用。它通常会弹出不应该出现的文本。我希望它在用户输入错误信息后显示出来。我想要这样,如果输入的数据无效,他们将不得不重新输入。

这是我目前掌握的代码。

/*
1. Declare variables for month 1, 2, and 3.
2. Declare variable for Total and Average Rainfall
3. Ask user to input name of months.
4. Then ask user to input inches of rain fall.
5. Add all inches and then divide by number of inches asked. In this case, 3.
6. Display average inches of rain for all months to user.
*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
 string month1, month2, month3;//Declared values for months aswell as total and average rainfall. 
 double month1Inch, month2Inch, month3Inch;
 double averageInches;
 double totalInches; 
 char c = 'y';
 do
{
    cout << setprecision(2) << fixed;
    cout << "Enter first month's name:";
    cin >> month1;
    cout << "Enter rain inches for " << month1 << ":";
    cin >> month1Inch;
    cout << "n";
    cout << "Enter second month's name:";
    cin >> month2;
    cout << "Enter rain inches for " << month2 << ":";
    cin >> month2Inch;
    cout << "n";
    cout << "Enter third month's name:";
    cin >> month3;
    cout << "Enter rain inches for " << month3 << ":";
    cin >> month3Inch;
    cout << "n";
    totalInches = (month1Inch + month2Inch + month3Inch);
    averageInches = (totalInches) / 3;//calculating the average
    //Display calculated data.
    cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl;
    cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
    cin >> c;

} while (c == 'Y'||c=='y');
if (c != 'Y' || c != 'y')
    cout << "you must enter the correct choice" << endl;
system("pause");
return 0;
}

我试着在"cout<<"下放一个if语句,你想重新计算吗?输入Y运行或输入N不运行。"<<endl;cin>>c;"但我得到了无限循环。

我没有收到任何错误代码。只是文本显示为"你想重新计算吗?"行和无限循环。

即使当我输入显示的数据时,我也会在某个地方得到一个无限循环。所以我删除了它。

听起来您想要验证Yes或No响应。这需要一个循环,只有当您有可接受的输入时才能退出。它与决定是否应该再次运行计算的循环是分开的。

int main() {
  // ...
  do {
    // ...
    do {
      cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
      cin >> c;
    } while (c != 'Y' && c != 'y' && c != 'N' && c != 'n');
  } while (c == 'Y'|| c=='y');
  system("pause");
  return 0;
}