1

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];
      }
11
  • 2
    Somehow your indentation is totally trashed. Is it possible to clean this up and make it more readable? Commented Jul 16, 2014 at 16:02
  • 1
    I fixed your indentation, but not your non-compilable code. I could try to fix it, but then I'd be making assumptions about how the code sample ends. Commented Jul 16, 2014 at 16:07
  • 1
    Is it on purpose that the user can only do one wrong entry ? What happens if he makes a wrong entry the second time ? Commented Jul 16, 2014 at 16:10
  • 1
    You should re-read the answer to your previous question (stackoverflow.com/a/24783190/624664) Commented Jul 16, 2014 at 16:11
  • 1
    @isme then the if (cin.fail()) is not sufficient. Use a while(cin.fail()) instead and get rid of your else because I suppose you want to print the value as soon as you succeed in any case. Commented Jul 16, 2014 at 16:17

2 Answers 2

1

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];
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.