C++ 流的粗略运用

/* 
 * 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
---------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值