C++IO流

C++IO流

// 使用文件IO流用文本及二进制方式演示读写配置文件
struct ServerInfo
{
    char _ip[32]; // ip
    int _port; // 端口
};
struct ConfigManager
{
public:
    ConfigManager(const char* configfile = "bitserver.config")
        :_configfile(configfile)
    {}
    void WriteBin(const ServerInfo& info)
    {
        // 这里注意使用二进制方式打开写
        ofstream ofs(_configfile, ifstream::out | ifstream::binary);
        ofs.write((const char*)&info, sizeof(ServerInfo));
        ofs.close();
    }
    void ReadBin(ServerInfo& info)
    {
        // 这里注意使用二进制方式打开读
        ifstream ifs(_configfile, ifstream::in | ifstream::binary);
        ifs.read((char*)&info, sizeof(ServerInfo));
        ifs.close();
    }
    void WriteText(const ServerInfo& info)
    {
        // 这里会发现IO流写整形比C语言那套就简单多了,
        // C 语言得先把整形itoa再写
        ofstream ofs(_configfile);
        ofs << info._ip << endl;
        ofs << info._port << endl;
        ofs.close();
    }
    void ReadText(ServerInfo& info)
    {
        // 这里会发现IO流读整形比C语言那套就简单多了,
    // C 语言得先读字符串,再atoi
        ifstream ifs(_configfile);
        ifs >> info._ip;
        ifs >> info._port;
        ifs.close();

    }
private:
    string _configfile; // 配置文件
};
int main()
{
    ConfigManager cfgMgr;
    ServerInfo wtinfo;
    ServerInfo rdinfo;
    strcpy(wtinfo._ip, "127.0.0.1");
    wtinfo._port = 80;
    // 二进制读写
    cfgMgr.WriteBin(wtinfo);
    cfgMgr.ReadBin(rdinfo);
    cout << rdinfo._ip << endl;
    cout << rdinfo._port << endl;
    // 文本读写
    cfgMgr.WriteText(wtinfo);
    cfgMgr.ReadText(rdinfo);
    cout << rdinfo._ip << endl;
    cout << rdinfo._port << endl;
    return 0;
}
stringstream

. 将数值类型数据格式化为字符串

#include<sstream>
int main()
{
	int a = 12345678;
	string sa;
	// 将一个整形变量转化为字符串,存储到string类对象中
	stringstream s;
	s << a;
	s >> sa;
	// clear()
	// 注意多次转换时,必须使用clear将上次转换状态清空掉
	// stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit
	// 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换
	// 但是clear()不会将stringstreams底层字符串清空掉

	// s.str("");
	// 将stringstream底层管理string对象设置成"", 
	// 否则多次转换时,会将结果全部累积在底层string对象中

	s.str("");
	s.clear(); // 清空s, 不清空会转化失败
	double d = 12.34;
	s << d;
	s >> sa;
	string sValue;
	sValue = s.str(); // str()方法:返回stringsteam中管理的string类型
	cout << sValue << endl;
	return 0;
}

字符串拼接

int main()
{
	stringstream sstream;
	// 将多个字符串放入 sstream 中
	sstream << "first" << " " << "string,";
	sstream << " second string";
	cout << "strResult is: " << sstream.str() << endl;
	// 清空 sstream
	sstream.str("");
	sstream << "third string";
	cout << "After clear, strResult is: " << sstream.str() << endl;
	return 0;
}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值