I almost sure this question had been ask, but after a long search I still can't find the answer. I extracted this piece of code from Accelerated C++, and I have a problem with terminating the while
loop. Code is here:
#include <iostream>
#include <vector>
using namespace std;
istream& read(istream& in, vector<double>& vec)
{
cout << "start reading" << endl;
if (in) {
vec.clear();
double x;
while (in >> x) {
cout << "x=" << x << endl;
vec.push_back(x);
}
in.clear();
}
cout << "end reading" << endl;
return in;
}
int main() {
vector<double> vec;
read(cin, vec);
return 0;
}
I input 1 2 3 4 5
type EOF (Ctrl-D on MacOS) the program does not terminate. I can continue typing values into the vector:
start reading
1 2 3 4 5 x=1
x=2
x=3
x=4
x=5
5
x=5
6
x=6
7
x=7
The closest question I found here: http://www.cplusplus.com/forum/beginner/49993/
Ok the problem was that in mac I should do the following: press ctrl-D to signal and end to stdin, and then the enter key to return the buffer. More: https://discussions.apple.com/thread/2361809