"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.