/* 代码如下:
* 思路; 先捕获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;
}
C++中 ostream 转换为 string 与 c字符串
最新推荐文章于 2024-06-29 15:18:41 发布