I am having difficulties in getting my program working properly. For the part of the project I am having difficulties with, I need to create a function that validates two different numbers input by the user. However in the whenever I run the program I get two errors going on.

One is that the input is first read as me inputting 0 (even though I didn't)

And the second is that it treats it runs the first input through the second inputs validation test

Function prototypes:

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);
}

And the function prototype in question:

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;
}

}
有帮助吗?

解决方案

Since both of them are independent of each other, you need to separate the into two functions for your purpose : validateChoice which consists of the first while loop and validateMonths which consists of second while loop.

If you want single function itself you need to pass appropriate parameter

int validate(int value, int lowLimit, int HighLimit)
{
    while(value < lowLimit || value > HighLimit)
    {
        //print error message here
        cin>> value;
    }
    return value;
}

In main, do

cin >> choice;
choice = validate(choice, 1, 4);

Similarly for months.

其他提示

You haven't shown how (if at all) you initialize choice and months before your do loop, but my guess is you haven't. Therefore here:

cin >> choice; 
validate(choice, months);

You are passing an uninitialized value as the second argument to validate. An uninitialized value could be anything; in your case, it seems to be zero.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top