我想从标准输入中读取一些数字,处理它们,然后读取下一串数字。从std :: cin读取多次 - 在Linux和Mac OS X上有不同的行为
我想出了解中的EOF
字符并清除eofbit,failbit和badbit的解决方案。下面的代码工作在Ubuntu 14.04与GCC 4.9.2:
#include <iostream>
#include <vector>
int main() {
std::vector<double> a;
std::vector<double>::iterator it;
double x;
while(std::cin >> x) {
a.push_back(x);
}
std::cout << "First bunch of numbers:" << std::endl;
for (it = a.begin(); it != a.end(); ++it) {
std::cout << *it << std::endl;
}
// get crap out of buffer
char s;
std::cin >> s;
std::cin.clear();
// go for it again
while (std::cin >> x) {
a.push_back(x);
}
std::cout << "All the numbers:" << std::endl;
for (it = a.begin(); it != a.end(); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
所以,在Ubuntu上我可以输入1<Return>2<Return>^D
,得到一些输出,类型3<Return>4<Return>^D
,获得更多的产出和程序终止。
在Mac OS 10.10然而,使用相同版本的GCC,该程序将不接受第二轮输入,但打^D
后第一时间的两倍数的第一序列输出。
- 为什么会有不一致的行为?是否有可能解决它?
- 惯用的接受两次输入的方式是什么?
- 在我的使用案例中,第一批数字最终可能会从文件或管道中读取。我怎样才能在该场景中交互式地要求额外的输入。
也许尝试调用'的std :: cin.clear()'发送后使用它之前, “EOF”是第一次? – Galik
这是控制台行为,而不是C++代码。在MacOS中,它可能在发送EOF之后关闭输入流[就像在Windows中一样](http://stackoverflow.com/questions/10147996/resume-reading-from-iostreamcin-after-ctrlz-eof-ignore-doesnt-work?rq = 1) –