ifstream&ofstream的基本使用
要使用fstream首先需要先将其与特定的文件进行绑定.如:
#include <fstream>
ifstream in_file( “c://input_file.txt” );
而对于输入流,目前知道的只能通过输入迭代器对其进行绑定,然后使用迭代器读入到容器中,如:
#include <iterator>
#include <vector>
vector< string > vec;
istream_iterator< string > is( in_file ); //注意要为迭代器指定类型
istream_iterator< string > eof; //若定义输入迭代器后不为其指定istream对象,便代表end-of-file
copy( is, eof, back_inserter( vec ) );
当然,输入迭代器也可以绑定cin,当此时我感觉其就是将cin中缓存的内容看作一个容器,通过迭代器来进行操作,但它并不等于cin,应该这样使用:
istream_iterator< string > is( cin );
istream_iterator< string > eos;
copy( is, eos, back_inserter( vec ) );
而不是这样使用
while( is >> str )
vec.push_back(str); //呵呵,我刚开始就犯了这样的错误
对于输出流,可以直接像使用cout一样,如:
ostream ofile( "output_file.txt" );
ofile << "HelloWorld!" ; //只要这样写就可以将 HelloWorld! 写入output_file.txt中
对于输出迭代器,只接触过下面这个例子:
ostream_iterator< string > os ( ofile, " " );
copy( vec.begin(), vec.end(), os ); //这样写之后每个string后都会加一个空格了
小结:
呵呵,也许是我反应太迟钝了,写完之后才觉得其实输入输出流应该跟cin、cout的操作差不多的,而输入输出迭代器主要是为了能够方便使用容器、算法等操作。