This is what I have done to read integers with std::cin
and store them in a vector:
int number;
vector<int>ivec;
while (cin>>number)
{
ivec.push_back(number);
}
for (auto v: ivec){
cout << v;
}
Then, I am stuck with the problem that how to stop entering integers and move to the next process of printing the vector out. Any pointer will be appreciated.
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 putscin
into the bad state. It can be recovered from using theclear
methode. The other way is making the reading of characters fromcin
fail (for example the end of a file that gets used as input). This putscin
into thefailed
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 usingstrtol
or astringstream
, and comparing for a magic stop-token (e.g. empty line, "end") to exit the loop.You can do it the following way
In Windows you have to press key combination
Ctrl + z
and in UNIX systemCtrl + d
Or you can introduce a sentinel. In this case the loop can look like
Please find a simple solution to your problem, let me know if you see any issue with this solution.
It depends on the terminal in use and the precise mechanism varies quite a lot but, conventionally, typing Ctrl+D (Linux) or Ctrl+Z (Windows) will result in an end-of-file "signal" being transmitted along the pipe, causing the EOF bit to be set on
cin
, and thus the nextcin >> number
attempt to fail.That will break the loop.
Conveniently, the same will happen if you ran your executable with redirected input from a file. Which is kind of the point.