Cin需要2个输入

时间:2014-02-19 19:53:43

标签: c++ cin

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

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

4 个答案:

答案 0 :(得分:0)

我希望它有所帮助:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试使用while循环

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

如果你只需要2次,只需添加一个计数器。

我希望它有所帮助。

答案 3 :(得分:0)

这应该做你想做的事

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