如何将输入验证包含在此代码中
How do I incorporate input validation in this code?
我试图在这个程序中实现输入验证,但结果总是出错。我尝试使用另一个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;
}
相关文章:
- 编译包含字符串的代码时遇到问题
- 在混合代码库中将C转换为C++时出现许多包含错误
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- 如何将外部代码包含在虚幻引擎4 C++项目中
- 如果代码包含多个复杂度循环,如何计算复杂度
- 如何使用 cmake 在代码中包含、构建和调试共享库 (.so)?
- 在 C++ 对象包装器中安全地包含 C 代码
- 为什么我的代码包含错误分段错误(核心转储)?
- 如何在此代码中包含 While 语句
- 在源文件中包含额外的调试信息,以便在代码::块中使用gdb进行调试
- 在Visual Studio代码中包含自定义c++库的问题
- 当我在结构中包含多个数组时,我的程序会跳过一堆代码
- C++:汇编代码包含断言结果
- 如何为代码包含负值?号码系统转换
- C++模板可以用于条件代码包含吗
- 如何将文件作为字符串和代码包含在cpp中
- C++代码包含错误
- c++宏:条件代码包含在表达式NOT语句中
- 端口C代码包含复数到c++
- 将模板代码包含在多个编译单元中,它将始终链接而不内联