Question

I am trying to make a function that will make sure a number is greater than zero, but whenever the user does not enter a number greater than zero they must enter a value twice before the code will continue. Please help!

int userInput()
{
    int goAhead = 0;
    int a;

    while (goAhead == 0)
    {
        cin >> a;
        if(a <= 0 )
        {
            cout << "The  can not be less than or equal to zero, enter another value: " << endl;
            cin >> a;
            cin.ignore();
        }
        else
        {
            // enter code here
            goAhead = 1;
        }
        return a;
    }
}
Était-ce utile?

La solution

I hope it helps:

    int userInput()
    {
        int a = 0;
        while(a <= 0) {
            cout << "Enter value greater than zero: " << endl;
            cin >> a ;
            if(a <= 0)
                cout << "Input incorrect. Please try again " << endl;
        } 
        return a;
    }

Autres conseils

    int userInput()
    {
        int a;
        int tries = 2; // this will count down to 0, which then return anything you want as an invalid answer

        do
        {
            cout << "enter value: ";
            cin >> a;

            if( a  > 0 ) 
            {
                return a;
            }
            else
            {
                if(--tries > 0)
                {
                    cout << "The can not be less than or equal to zero" << endl;
                }
                else
                {
                    cout << "returning -1" << endl;
                    return -1;
                }
            }
        }while (true);
    }

Try using a while loop

cin>>a;
while(a<=0)
{
System.out.println("Please enter again");
cin>>a;
}

if you want only 2 more times, just add a counter.

I hope it was helpful.

this should do what you are trying to

int userInput()
{
     int a;
     cin >> a;
     while(a <= 0 )
     {
         cout << "The  can not be less than or equal to zero, enter another value: "<< endl;
         cin >> a;
         cin.ignore();
     }
     return a;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top