2010-09-25 41 views

回答

3

C++流是不能與C STDIO流兼容。換句話說,您不能使用帶有FILE*fread的C++迭代器。但是,如果您使用C++ std::fstream工具以及istream_iterator,可以使用插入迭代器插入到C++容器中。

假設你有一個包含ASCII文本數字用空格隔開輸入文件「input.txt中」,你可以這樣做:

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <iterator> 

int main() 
{ 
std::ifstream ifs("input.txt"); 
std::vector<int> vec; 
    // read in the numbers from disk 
std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec)); 
    // now output the integers 
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n")); 
} 
+0

您可以指定流的末尾便於閱讀例如由5個整數? – user963241 2010-09-25 21:37:48

+0

是的,您可以使用包含計數參數的'std :: copy_n'。 – 2010-09-25 21:39:43

1

不,你不能。像這樣存儲int基本上是不可移植的。如果您使用big-endian機器編寫文件並嘗試使用little-endian機器讀取它,您的代碼將會中斷。

但沒有人阻止你。只需定義自己的前向迭代器即可從istream中讀取二進制文件。您可能會希望停止使用FILE和fread/fopen/fclose函數,因爲它們來自C時代。

,那麼你就可以寫:

std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >);