简体   繁体   中英

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

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM