C++ ostream类型数据 转化为 string类型数据与c字符串形式

/*	代码如下:
*	思路; 先捕获ostream数据, 再将它进行转换为期望的类型数据
*/

#include <iostream>
#include <sstream>	// ostringstream 类型
#include <strstream>// ostrstream 类型
#include <string>

// ostream 转 char*字符串
void ostreamTchar(std::ostream& os) {
	char* a = { (char*)"" };
    
    //std::ends 是字符串的结束符, 以免内存泄露!
	os << a << std::ends;
}

// ostream 转 string
void ostreamTstring(std::ostream& os) {
	std::string a = "";
	os << a;
}

int main(void) {
	using namespace std;

	//ostrstream os;	//1
	ostringstream os;	//2

	//ostreamTchar(os);	//1
	ostreamTstring(os);	//2

	// 都是使用.str()输出字符串, 两种效果区别不大
	cout << os.str();

	return 0;
}
原创文章 6 获赞 5 访问量 175

猜你喜欢

转载自blog.csdn.net/qq_36394394/article/details/105668896