Cin 需要 2 个输入

Cin requires 2 inputs

本文关键字:输入 需要 Cin      更新时间:2023-10-16

我正在尝试创建一个函数来确保数字大于零,但是每当用户不输入大于零的数字时,他们必须输入两次值才能继续代码。请帮忙!

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;
    }
}
我希望

它有所帮助:

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

尝试使用 while 循环

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

如果您只想再增加 2 次,只需添加一个计数器。

我希望它有所帮助。

这应该做你想做的事情

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