End of stream detection

I am trying to read in a stream of ints of unknown length, then print each one on a separate line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> numbers;
  int index = 0;
  int newNum;
  while (!cin.eof()) {
    cin >> newNum;
    numbers.push_back(newNum);
    index++;
  }

  for (int i = 0; i < index; i++) {
    cout << numbers[i] << endl;
  }

  return 0;

}


I input a stream of random ints and press enter and the cursor in the console just moves to the next line and nothing is displayed. I have also tried using a while (true) construct, but I get the same results. I do not know if the problem is in the vector or if I am not using cin.eof() correctly. Any help will by greatly appreciated.
1) streams associated with terminal input does not have "end": if current input is exhausted, it simply asks for more.

2) Do not loop on eof(). It will lead to last number getting read twice. Loop on input operation: while(std::cin >> newNum)

3) You can use stream redirection to send arbitrary string or file to standard input instead of using terminal window for input
Or, if you are using windows, press Enter, Ctrl+z, Enter when you are done
Other way is to read single line containing your numbers and then parse it.
Last edited on
Usually you have to press a key combination such as Ctrl+D or Ctrl+Z to mark the end of the stream.

Checking EOF as a loop condition is usually not the correct way of doing it because the EOF flag might not be set until you try to read past the end of the stream so you end up running the loop one extra time. If you instead put the read operation as a loop condition it will read the correct number of times (until the read operation fails).
1
2
3
4
while (cin >> newNum) {
	numbers.push_back(newNum);
	index++;
}
Thank you for your help. I have made the recommended changes to the loop, but I am still having the same problem.
Did you send endstream marker manually?
MiiNiPaa wrote:
Or, if you are using windows, press Enter, Ctrl+z, Enter when you are done
That fixed it. I thought the terminal character would be added when the string was entered. Thank you for your help.
Topic archived. No new replies allowed.