1

Hi I try to create a input function for my function through vector.

However, I don't know why my input become infinite loop?

do {            
    cout << "Please enter the next number: ";
    cin >> num;
    number.push_back(num);
    cout << "Do you want to end? enter 0 to continue.";
    dec = NULL;
    cin >> dec;
} while(dec == 0);
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    if dec is not a pointer then you should not use `dec = NULL;`. If you cant replace `NULL` with `nullptr` your code should be considered broken. – NathanOliver Apr 14 '15 at 16:59
  • 1
    You should [add some concrete inputs](http://stackoverflow.com/posts/29633122/edit) given with your question, when your code shows this behavior. – πάντα ῥεῖ Apr 14 '15 at 17:28
  • To give more explanation why I've rolled back your question to it's original state, please follow the according discussion on [Meta SO](http://meta.stackoverflow.com/questions/290240/should-i-rollback-the-ops-edits-if-they-just-replicate-my-answers-proposed-ch). – πάντα ῥεῖ Apr 14 '15 at 21:50

1 Answers1

1

"I don't know why my input become infinite loop."

The only reason I can imagine is, that any incorrect input sets cin to fail state. In this case (e.g. an invalid number was entered, or just ENTER was pressed) cin is set to fail state and your value in dec won't change evermore. Once cin is in fail state any subsequent input operations will fail respectively, and the subject for input won't be changed.

To be proof against such behavior, you have to clear() the std::istream's state, and read up to a safe point, before proceeding (see also: How to test whether stringstream operator>> has parsed a bad type and skip it):

do {
    cout << "Please enter the next number: ";
    if(cin >> num) {
        number.push_back(num);
    }
    else {
       cerr << "Invalid input, enter a number please." << std::endl;
       std::string dummy;  
       cin.clear();
       cin >> dummy;
    }
    cout << "Do you want to end? enter 0 to continue.";
    dec = -1;
    if(!(cin >> dec)) {
       std::string dummy;  
       cin.clear();
       cin >> dummy;
       break; // Escape from the loop if anything other than 0 was
              // typed in
    }
} while(dec == 0);

Here are three working demos with different inputs to end the loop:

1st Input:

1
0
2
0
3
0
4

ENTER

2nd Input:

1
0
2
0
3
0
4
xyz

3rd Input

1
0
2
0
3
0
4
42

The loop is finite, and output for all of the above is

1234

You should also note that I have changed bool dec; to int dec;, but that's probably a minor point.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190