将变量添加到作为提示的输入参数

时间:2014-02-24 02:18:37

标签: c++

我有这个函数来验证整数输入。如您所见,有三个输入参数。 (提示,下限和上限)

double getValidNumber( string prompt, double lowerLimit, double upperLimit)
{
    double num;
    cout << prompt;
    cin >> num;


    while (num < lowerLimit) {
    cout << "Entry must be greater than or equal to " << lowerLimit << endl;
    cout << prompt;
    cin >> num;
    }
    while (num > upperLimit)
    {
    cout << "Entry must be less than or equal to " << upperLimit << endl;
    cout << prompt;
    cin >> num;
    }

    return num;
}

其中一个提示还需要一个变量(maxDays),其余的是一个字符串。此调用是从主

进行的
//calls function to validate year of pickup
year = getValidNumber
("Enter pick up year (2014-2024): ", 2014 , 2024);

//calls function to validate month of pickup
month = getValidNumber
("Enter pick up month (1-12):  ", 1 , 12);

//calls function to get max days in month
maxDays = daysInMonth (year, month);

// If a user inputs 2014, 2 (for Feb) there are only 28 days this year
// I need the prompt to be "Enter pick up day (1-28): 
//calls function to validate pickup day is within month
day = getValidNumber
("Enter pick up day (1- maxDays)", 1, maxDays);

我不确定如何在此提示中输入变量。

3 个答案:

答案 0 :(得分:0)

我建议你修改你的那个功能..

double getValidNumber( string prompt, double lowerLimit, double upperLimit)
{
    double num;
    while (true)
    {
         cout << prompt;
         cin >> num;
         if (num < lowerLimit)
         {
             cout << "Entry must be greater than or equal to " << lowerLimit << endl;
         }
         else if (num > upperLimit)
         {
             cout << "Entry must be less than or equal to " << lowerLimit << endl;
         }
         else
         {
             return num;
         }
    }
}

答案 1 :(得分:0)

您的要求不明确。你是什​​么意思:

  

我不确定如何在此提示中输入变量。

答案 2 :(得分:0)

(因为我无法在评论中格式化代码)有很多方法可以解决您的解决方案。一种方法是你可以编写另一个名为getValidNumberDay()函数的函数,如下所示:

double getValidNumberDay( string prompt, double lowerLimit, double upperLimit)
{
    double num;
    bool choice = 0;
    while (choice == 0) {
        cout << prompt << upperLimit << ")";
        cin >> num;
        if (num < lowerLimit)
        {
            cout << "Entry must be greater than or equal to " << lowerLimit << endl;
            cout << prompt;
            cin >> num;
        }
        else if (num > upperLimit)
        {
            cout << "Entry must be less than or equal to " << upperLimit << endl;
            cout << prompt;
            cin >> num;
        }
        else
        {
            choice = 1;
        }
    }
    return num;
}

然后,使用maxDays重写您的函数调用,如下所示:

day = getValidNumberDay
("Enter pick up day (1- ", 1, maxDays);

那应该可以解决问题!