C++ 流的粗略运用

来源:互联网 发布:java给文件夹重命名 编辑:程序博客网 时间:2024/06/03 13:08
/*  * File:   main.cpp * Author: Vicky.H * Email:  eclipser@163.com */#include <iostream>#include <fstream>#include <sstream>#include <cstring>class A {public:    friend std::ostream& operator<<(std::ostream& os, const A& ref);    friend std::istream& operator>>(std::istream& is, A& ref);    A() { }    A(const char* name, short age) : age(age) {        strcpy(this->name, name);    }private:    char name[21];    short age;};std::ostream& operator<<(std::ostream& os, const A& ref) {    os << ref.name << '\n' /**需要换行符*/ << ref.age;    return os;}std::istream& operator>>(std::istream& is, A& ref) {    is >> ref.name >> ref.age;    return is;}/* *  */int main(void) {    // 文件的输入输出流    std::ofstream ofs("./tmp.txt", std::ios::trunc | std::ios::binary);    ofs << A("Lily", 25); // 将对象输入到文件中    ofs.flush();    ofs.close();        std::ifstream ifs("./tmp.txt", std::ios::in | std::ios::binary);    A a2;    ifs >> a2; //  读取文件内容,将其转换为对象    ifs.close();    std::cout << a2 << std::endl;        std::cout << "---------------------------" << std::endl;        // 字符的输入输出流    std::ostringstream oss; // 将对象输入到字符输出流    oss << A("string",99);    oss.flush(); // 刷新输出缓冲区    std::cout << oss.str() << std::endl;        std::string str("test\n123");     std::istringstream iss(str); // 将字符串输入到字符输入流    A a3;    iss >> a3; // 字符输入流写入到对象    iss.sync(); // 刷新输入缓冲区    std::cout << a3 << std::endl;        std::cout << "---------------------------" << std::endl;            // 控制台输入输出流    std::cout << A("Vicky", 25) << std::endl;    A a;    std::cout << "input A just like:\nVicky\n25" << std::endl;    std::cin >> a;    std::cout << a << std::endl;    std::cout << "---------------------------" << std::endl;        return 0;}

Lily
25
---------------------------
string
99
test
123
---------------------------
Vicky
25
input A just like:
Vicky
25
ooxx
1002
ooxx
1002
---------------------------
原创粉丝点击