#include <iostream>
#include <vector>
usingnamespace 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.
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++;
}