【发布时间】:2016-08-14 10:04:15
【问题描述】:
我想从标准输入中读取一些数字,处理它们,然后读取下一组数字。
我想出了读取char 中的EOF 字符并清除eofbit、failbit 和badbit 的解决方案。以下代码适用于带有 GCC 4.9.2 的 Ubuntu 14.04:
#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 版本,程序将不接受第二轮输入,而是在点击 @ 后两次输出第一个数字序列987654327@第一次。
- 为什么会出现不一致的行为?是否有可能解决它?
- 接受两次输入的惯用方式是什么?
- 在我的用例中,第一串数字最终可能会从文件或管道中读取。在那种情况下,我怎样才能以交互方式请求额外的输入。
【问题讨论】:
-
第一次发送
EOF后,在使用之前尝试调用std::cin.clear()? -
这是控制台行为,不是 C++ 代码。在 MacOS 中,它可能在发送 EOF like in Windows 后关闭输入流