我想從標準輸入中讀取一些數字,處理它們,然後讀取下一串數字。從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) –