8.29 auto关键字 lambda 类型转换 标准模板库 文件操作

8.29 auto关键字 lambda 类型转换 标准模板库 文件操作_第1张图片 

#include 
#include 
#include 

using namespace std;

class Stu
{
    friend ofstream &operator<<(ofstream &ofs, Stu &v);
    friend int operator>>(ifstream &ifs, Stu &t);
    friend ostream &operator<<(ostream &cout, const Stu &O);
    string name;
    int age;
public:
    Stu() {}
    Stu(string name, int age):name(name), age(age){}
};

ofstream &operator<<(ofstream &ofs, Stu &v){
    ofs << v.name << endl << v.age << endl;
    return ofs;
}

int operator>>(ifstream &ifs, Stu &t){
    if(!(ifs >> t.name))
        return 0;
    ifs >> t.age;
    return 1;
}

ostream &operator<<(ostream &cout, const Stu &O){
    cout << O.name << endl;
    cout << O.age << endl;
    return cout;
}

int main()
{
    vector v;
    v.push_back(Stu("zhangsan",18));
    v.push_back(Stu("lisi",18));
    v.push_back(Stu("wangwu",18));

    ofstream ofs;
    ofs.open("E:/Cdaima/1.txt", ios::out);
    vector::iterator iter = v.begin();
    while(iter != v.end()){
        ofs << *iter++;
    }
    ofs.close();

    ifstream ifs;
    ifs.open("E:/Cdaima/1.txt", ios::in);
    vector v2;
    Stu t;
    while(ifs >> t){
        v2.push_back(t);
    }

    iter = v2.begin();
    while(iter != v2.end()){
        cout << *iter++ << endl;
    }
    return 0;
}

8.29 auto关键字 lambda 类型转换 标准模板库 文件操作_第2张图片

你可能感兴趣的:(c++)