isme
isme

Reputation: 190

Limit input to only numbers

This is part of my input value, what i want to do is to only input 0-9 however when i put an alphabet or any invalid key, they program works fine it ask to re enter.

invalid input please re-enter:

however this time when i re-enter it print out:[ 6.95324e-310 2 3 4 5 ]

here are the code:

int main()
{
   int aSize=5;
   double aArray[aSize];
   double value;

   for(int i=0;i<aSize;i++)
   {
      cout<<"enter value of slot"<<i+1<<": ";
      cin>>value;
      if(cin.fail())
      {
         cin.clear();
         cin.ignore(numeric_limits<streamsize>::max(), '\n');
         cout<<"invalid input please re-enter: ";
         cin>>value;
      }
      else
      {
         aArray[i] = value;
         cout<<"value of aArray: "<<aArray[i];
      }

Upvotes: 1

Views: 1435

Answers (2)

mrVoid
mrVoid

Reputation: 995

Fix the code flow, not all paths are supported.

int main() {
  int aSize=5;
  double aArray[aSize];
  double value;

  for(int i=0;i<aSize;i++) {
    cout<<"enter value of slot"<<i+1<<": ";
    cin>>value;
// repeat handling of failure
    while (cin.fail()) {
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
      cout<<"invalid input please re-enter: "; 
// at this point we want to get back to fail
      cin>>value;
    }
    aArray[i] = value;
    cout<<"value of aArray: "<<aArray[i];

}

Upvotes: 0

Christophe
Christophe

Reputation: 73436

Try this:

    for (int i = 0; i < aSize; i++)
    {
        cout << "enter value of slot" << i + 1 << ": ";
        cin >> value;
        while (cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "invalid input please re-enter: ";
            cin >> value;
        }
        aArray[i] = value;
        cout << "value of aArray: " << aArray[i];
    }

Upvotes: 1

Related Questions