向字符串输出
将字符串作为输出流的目标,可以实现将其他数据类型转换为字符串的功能
字符串输出流( ostringstream )
- 用于构造字符串
- 功能
- 支持ofstream类的除open、close外的所有操作
- str函数可以返回当前已构造的字符串
- 典型应用
- 将数值转换为字符串
例:用ostringstream将数值转换为字符串
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//函数模板toString可以将各种支持“<<“插入符的类型的对象转换为字符串。
template <class T>
inline string toString(const T &v) {
ostringstream os; //创建字符串输出流
os << v; //将变量v的值写入字符串流
return os.str(); //返回输出流生成的字符串
}
int main() {
string str1 = toString(5);
cout << str1 << endl;
string str2 = toString(1.2);
cout << str2 << endl;
return 0;
}
/*
输出结果:
5
1.2
*/