[英]Terminating a while(cin >> s) loop. Accelerated C++
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. 我从Accelerated C ++中提取了这段代码,但是在终止while
循环时遇到了问题。 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. 我输入1 2 3 4 5
键入EOF(在MacOS上为Ctrl-D),程序不会终止。 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/ 我在这里找到的最接近的问题: 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. 好的问题是在Mac中我应该执行以下操作:按ctrl-D发出信号并结束到stdin,然后按Enter键返回缓冲区。 More: https://discussions.apple.com/thread/2361809 更多: https : //discussions.apple.com/thread/2361809
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.