C++11——IO标准库

使用fstream代替iostream&

我们可以在需要原始类型的对象的地方使用继承类型的对象。这一事实意味着可以代表相应的fstream(或sstream)类型调用被编写以获取其中一个iostream类型的引用(或指针)的函数。如果我们调用一个参数为ostream&函数,我们可以给该函数传递一个ofstream对象。istream&ifstream之间也有类似的关系。
例如我们使用readprint函数来读取和写入命名文件。在这个例子中,我们假设输入和输出文件的名称作为参数传递给了main函数:

Code:
    ifstream input(argv[1]);    // open the file of sales transactions
    ofstream output(argv[2]);   // open the output file
    Sales_data total;           // variable to hold the running sum
    if (read(input, total)) {   // read the first transaction
        Sales_data trans;       // variable to hold data for the next transaction
        while(read(input, trans)) {    // read the remaining transactions
            if (total.isbn() == trans.isbn()) //  check isbns
                total.combine(trans);  // update the running total
            else {
                print(output, total) << endl; //  print the results
                total = trans;        // process the next book
            }
        }
        print(output, total) << endl; // print the last transaction
    } else  // there was no input
        cerr << "No data?!" << endl;

上述代码中,readprint函数定义的参数分别为istream&ostream&。但是我们可以将fstream对象传递给这些函数

参考文献

[1] Lippman S B , Josée Lajoie, Moo B E . C++ Primer (5th Edition)[J]. 2013.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。