This is what I have done to read integers with std::cin
and store them in a vector:
int number;
vectorivec;
while (cin>>number)
{
The code you posted reads numbers from cin
as long as it succeeds. There are two ways to have it stop succeeding: If you enter something that is not a number, reading data still succeeds, but converting it to number fails. This puts cin
into the bad state. It can be recovered from using the clear
methode. The other way is making the reading of characters from cin
fail (for example the end of a file that gets used as input). This puts cin
into the failed
state. Usually, recovering from a failed state is impossible.
To produce the you can no longer read state at end of file when entering data at the keyboard, operating system specific methods have to be used (likely Control-D or Control-Z). This is final for the invocation of your program.
If you need a way for the user to signal: "Please go on, but let me enter other stuff later", the most clean way is likely reading cin
line-by-line and parse the input using strtol
or a stringstream
, and comparing for a magic stop-token (e.g. empty line, "end") to exit the loop.