0 概述
C++引入了ostringstream、istringstream、stringstream
这三个类,头文件<sstream>
。
1 istringstream
istringstream类执行C++风格的串流的输入操作。
- 定义类型:
typedef basic_istringstream<char> istringstream;
- 继承关系:
- 示例代码:
string s = "I come from china";
istringstream is(s);
cout << s << endl;
while (is >> s)
cout << s << endl;
- 执行结果:
2 ostringstream
ostringstream类执行C风格的串流的输出操作。
- 定义类型:
typedef basic_ostringstream<char> ostringstream;
- 继承关系:
- 示例代码:
double pi = 3.141592653589793;
ostringstream s1;
s1.setf(ios::fixed); //显示小数
s1.precision(10); //10位精度
s1 << "pi:" << pi;
string show = s1.str();
cout << "show:" << show << endl;
- 执行结果:
3 stringstream
strstream类支持C风格的串流的输入输出操作。
- 定义类型:
typedef basic_stringstream<char> stringstream;
- 继承关系:
- 示例代码:
double pi = 3.141592653589793;
stringstream s1;
s1.setf(ios::fixed); //显示小数
s1.precision(10);
s1 << "pi:" << pi;
string show = s1.str();
cout << "show:" << show << endl;
string s = "I come from china";
stringstream is(s);
cout << s << endl;
while (is >> s)
cout << s << endl;
- 执行结果:
4 类型转换
类型转换过程
// 字符转数字
ss << string("15");
int num;
ss >> num;
// 如果多次使用ss进行转换,需使用clear()函数对内容清空
ss.clear();
// 数字转字符
ss << 67;
string str;
ss >> str;