C++的输入输出由标准库提供。标准库定义了一族类型,支持对文件和控制窗口等设备的读写,还定义了其他一些类型,使string对象能够像文件一样操作,从而使我们无须IO就能实现数据与字符之间的转换。IO类型在三个独立的头文件中定义,iostream定义读写控制窗口的类型,fstream定义读写已命名文件的类型,而sstream所定义的类型则用于读写存储在内存中的stream对象。首先看一下各个类之间的继承关系:
使用流应该注意到的问题有:
1. IO对象不可复制或赋值。
这表示:(1)由于只有支持复制的元素类型可以存储在vector或其他容器里,因此vector不能存储在vector或其他容器中。(2)形参或返回类型也不能为流类型,如果需要传递或返回IO对象,则必须传递或返回该对象的指针或引用。(怪不得我印象中看到的函数参数都是istream&这样子的)
2. 流的条件状态
可以如下管理输入操作:
int ival;
while( cin>>ival, !cin.eof() ){
if( cin.bad() )
throw runtime_error( "IO stream corrupted" );
if( cin.fail() ){
cerr << "bad data, try again";
cin.clear( istream::failbit);
continue;
}
//ok to process ival
}
3. 输出缓冲区的管理
cout << "hi!" << flush; //flushes the buffer, adds no data
cout << "hi!" <<endl; //inserts a newline then flushes
cout << "hi!" <<ends; //inserts a null, then flushes
cout << unibuf << "first" << "second" <<nounibuf;
//equivalent to :
cout << "first" << flush << "second" << flush;
//ties a i/o stream to an o/i stream
cin.tie(&cout);
cin.tie(0); //break tie to cout
4. 文件流
文件流必须跟某一特定文件绑定(通过文件名),可以在初始化时绑定,也可以在后期open的时候绑定。
ifstream infile( ifile.c_str() ); //ifile is a string object
ofstream outfile;
outfile.open( "out" ); //associates a file when open
//check if the file is successfully opened
if( !infile ){
//the file is not opened to use
}
//re-associate the stream with a new file
infile.close();
infile.open( "next" );
//clear the state of the stream
//files is a vector that stores names of the files, it is an iterator from begin
ifstream input;
vector<string> :: const_iterator it = files.begin();
while( it != files.end() ){
input.open( it->c_str() );
if( !input )
break;
while( input >> s )
process(s);
input.close();
input.clear(); //clear the state of the stream
++it;
}
5. 文件模式
在打开文件时,无论是调用open还是以文件名作为流初始化的一部分,都需指定文件模式。每个fstream类都定义了一组表示不同模式的值,用于指定流打开的不同模式。如下:
out、trunc、app模式只能用于指定与ofstream或fstream对象关联的文件;in模式只能用于指定与ifstream或fstream对象关联的文件。所有的文件都可以用ate或binary模式打开。ate模式只有在打开时有效:文件打开后将定位在文件尾。
6. 字符串流
字符串流为字符串的操作提供了更加自由方便的处理方法,把字符串保存在字符串流中,就相当于把数据缓存起来,然后可以再次作为输入,决定处理方式。例如,我们需要读取一行数据,然后再对这行数据进行逐个处理;或者是将字符串进行转换或格式化。
//片断一:处理行,再处理行中的每个单词
string line, word;
while( getline(cin, line) ){
istringstream stream(line);
while( stream >> word )
process(word);
}
//片断二:字符串流提供的格式转换
int val1 = 300, val2 = 400;
ostringstream format_message;
format_message << "val1: "<<val1 << "\n"
<< "val2: "<<val2 << \n";
istringstream input_istream( format_message.str() );
string dump;
input_istream >> dump >> val2 >> dump >> val1;
cout<< val1 << " " << val2 <<endl;
http://philoscience.iteye.com/category/176811