IO标准库:字符串流


一、字符串流中的string对象是一份副本,而不是对原来的string对象的引用:

void test_sstream()
{
	std::string s1("abc");
	std::stringstream ss(s1, std::stringstream::in | std::stringstream::out); // 对于stringstream默认是in和out的组合模式
	std::string s2 = ss.str();
	if( &s1 ==  &s2)
	{
		std::cout << "s1 and s2 have the same memory address!" << std::endl;
	} else 
	{
		std::cout << &s1 << std::endl; // 0x0032f834
		std::cout << &s2 << std::endl; // 0x0032f75c
	}
	// s2是对s1的复制,并不是s2指向s1或s2引用s1
	// 故在字符串流中对字符串的更改并不改变原来string对象

	ss.put('1');
	std::string s3 = ss.str();
	if( &s2 == &s3 )
	{
		std::cout << "s2 and s3 have the same memory address!" << std::endl;
	} else
	{
		// 字符串流中的各种写操作,都会导致字符流复制原来的string对象,而不是对原来的string
		// 对象进行修改
		std::cout << &s2 << std::endl; // 0x0032f75c
		std::cout << &s3 << std::endl; // 0x0039f7a4
	}

	std::cout << s1 << std::endl; // abc
	std::cout << s2 << std::endl; // abc
	std::cout << s3 << std::endl; // 1bc
}

二、从string类型到基本类型的转换

void string_to_basetype()
{
	// 1)string类型转成int
	std::stringstream ss("123");
	int int_result;
	ss >> int_result;
	std::cout << int_result << std::endl;	// 123

	// 2)string类型转成double
	ss.str("");		// 推荐重用一个stringstream类型进行多种转换,因为重新重建stringstream对象会耗cpu,
	ss.clear();		// 但在转换之前要清空源string对象和重新设置stringstream的goodbit状态值
		 
	double dou_result;
	ss.str("3.14");
	ss >> dou_result;
	std::cout << dou_result << std::endl;	// 3.14

	// 3)string转成bool:注意不要使用str("true")或str("false")
	ss.str("");
	ss.clear();
	bool bool_result;
	//ss.str("true");	// error
	ss.str("1");		// right
	ss >> bool_result;
	std::cout << bool_result << std::endl;	// 1
}

三、基本类型转成string

void basetype_to_string()
{
	int i(1);
	std::stringstream ss;
	ss << i; // 把值传递到流中
	std::string s = ss.str();
	std::cout << s << std::endl;	//1
}

四、基本类型转成char数组

void basetype_to_char_arr()
{
	char arr[4]; // 666,是三位数字,则char数组的长度应该大于或等于4
	std::stringstream ss;
	ss << 666;
	ss >> arr;
	std::cout << arr << std::endl;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值