如何修正输入C ++(基本)的提示

时间:2019-02-02 21:10:39

标签: c++ input

我正在尝试编写一个循环,以便提示用户最多输入4次,但我遇到的问题是,如果用户输入的不是预期的double值(用于估计),我需要输出消息这不是正确的类型。我要输出此消息并仍然提示和接收多达4次尝试用于估计。

#include <iostream>
using namespace std;


int
main ()
{

 double estimate; 
 double increment;
 int numRows; 

 const int minRows = 1;
 const int maxRows = 100; 
 const double minInc = 0.1;
 const double maxInc = 10.0; 
 const double minEst = -10.0; 
 const double maxEst = 10.0; 

 string inputFile;
 int numTries = 0;



 while (numTries < 4) 
{
   numTries++;
   cout << "Enter initial estimate of root : "; 
   cin >> estimate; 

   if (!(cin.fail())) 
   { 
     if ((estimate >= minEst) && (estimate <= maxEst))
     {
       break;
     }
     else
     {
       if (numTries == 4)
       { 
         cout << "ERROR: Exceeded max number of tries entering data" << endl;
         return 0;
       }
       cout << "" << endl;
       cout << "Value you entered was not in range\n";
       cout << fixed << setprecision(3) << minEst << " <= initial estimate <= " << maxEst << endl;
     }
   }
   else
   {

   cout << "The initial estimate was not a number\n";
   cin.clear();

   }
}

}

此代码的结果:

Enter initial estimate of root : y
The initial estimate was not a number
Enter initial estimate of root : The initial estimate was not a number
Enter initial estimate of root : The initial estimate was not a number
Enter initial estimate of root : The initial estimate was not a number

我想要:

Enter initial estimate of root : y
The initial estimate was not a number
Enter initial estimate of root : 

并让用户输入下一个值!

1 个答案:

答案 0 :(得分:0)

您还需要使用无效字符。对于发生错误的情况,添加了cin.get()来执行此操作,如下面的代码所示。

#include <iostream>
using namespace std;


int
main ()
{

    double estimate;
    double increment;
    int numRows;

    const int minRows = 1;
    const int maxRows = 100;
    const double minInc = 0.1;
    const double maxInc = 10.0;
    const double minEst = -10.0;
    const double maxEst = 10.0;

    string inputFile;
    int numTries = 0;



    while (numTries < 4)
    {
        numTries++;
        cout << "Enter initial estimate of root : ";
        cin >> estimate;

        if (!(cin.fail()))
        {
            if ((estimate >= minEst) && (estimate <= maxEst))
            {
                break;
            }
            else
            {
                if (numTries == 4)
                {
                    cout << "ERROR: Exceeded max number of tries entering data" << endl;
                    return 0;
                }
                cout << "" << endl;
                cout << "Value you entered was not in range\n";
                cout << fixed << minEst << " <= initial estimate <= " << maxEst << endl;
            }
        } else {
            cout << "The initial estimate was not a number\n";
            cin.clear();
            std::cin.get();
        }
    }
}