int ReadNumbers()
{
int num;
vector<int> x;
cout << "Enter Numbers" << '\n';
while(cin >> num)
{
x.push_back(num);
cout << num << " was added to the Vector" << '\n';
}
}
The while loop is expected to terminate when the user provides an Invalid Input. But this while loop behaves unexpectedly when the user provides a 'Newline' input (by pressing Enter) and becomes an infinite loop. How can I prevent this from happening? Also I've heard that expecting invalid inputs isn't good code design. Is this true? If yes, then how can I solve my question without expecting Invalid Inputs?
Why did you decide that the loop behaves unexpectedly when the user enter a new;ine? The new line is a white space character that will be skipped. It is expected behavior of this loop.
Because we are entering an unknown number of inputs, the loop has to terminate at some point when the user is finished with his inputs. That is what I want. But entering a newline in this case causes the while loop to behave unexpectedly.
But just pressing enter will not cause the stream to enter an error state. To exit this loop you will need to enter some invalid value or perhaps by signaling eof() by using the control D or control Z key combination.
When you use cin where a boolean value is expected, it returns the error state of the stream. If it's not in an error state it evaluates to true, and if it is in an error state it evaluates to false.
You're doing essentially the same thing with while ( cin >> num ).
cin.peek() returns the next character in the input stream without extracting it.
So while (std::cin && std::cin.peek() != '\n') could be restated in English as: while cin is not in an error state and the next character in the stream is not a newline.
Ok Thanks! :) By the way, can anyone suggest an introductory book for learning C++? I'm already using C++ Primer but I didnt like it (I've read the first 4 chapters )