我很难使我的程序正常工作。对于项目中我遇到困难的部分,我需要创建一个函数来验证用户输入的两个不同的数字。然而,每当我运行程序时,我就会看到两个错误。
一个是输入时首先读取输入0(尽管我没有)。
第二个是它通过第二个输入验证测试来运行第一个输入。
功能原型:
int validate(int , int);Main:
do
{
//display the menu
displayMenu();
cin >> choice;
validate(choice, months);
// process the user's choice
if (choice != QUIT_CHOICE)
{
// get the number of months
cout << over3 << "For how many months? ";
cin >> months;
validate(choice, months);
}以及所讨论的功能原型:
int validate(int choice, int months)
{
while (choice < 1 || choice > 4)
{
cout << over3 << choice << " is not between 1 and 4! Try again: ";
cin >> choice;
}
while (months < 1 || months > 12)
{
cout << over3 << months << " is not between 1 and 12! Try again: ";
cin >> months;
}
}发布于 2014-04-09 18:04:59
由于这两个函数是相互独立的,因此您需要将这两个函数分离为两个函数:由第一个while循环组成的validateChoice和由第二个while循环组成的validateMonths。
如果您想要单个函数本身,则需要传递适当的参数。
int validate(int value, int lowLimit, int HighLimit)
{
while(value < lowLimit || value > HighLimit)
{
//print error message here
cin>> value;
}
return value;
}总体来说,做
cin >> choice;
choice = validate(choice, 1, 4);同样适用于months。
发布于 2014-04-09 18:07:21
您还没有展示(如果有的话)如何在您的choice循环之前初始化do和months,但我猜没有。因此,这里:
cin >> choice;
validate(choice, months);您将一个未初始化的值作为第二个参数传递给validate。未初始化的值可以是任何值;在您的示例中,它似乎是零。
https://stackoverflow.com/questions/22970316
复制相似问题