一、介绍
<sstream> 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作, stringstream 主要用来进行数据类型转换。由于 stringstream 使用 string 对象来代替字符数组(snprintf方式),可以避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。
二、stringstream分割字符串
2.1 如果是空格,可以直接分割
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
string str = "i am a boy";
stringstream is(str);
string s;
while (is >> s) { // 输出流
cout << s << endl;
}
system("pause");
return 0;
}
2.2 如果输入的字符串要分别输出的话,必须使用 sstream.str("")来清空 stringstream
stringstream sstream;
int first, second;
// 插入字符串
sstream << "456"; // 转换为int类型
sstream >> first;
cout << first << endl;
// 清空 sstream
sstream.str("") //等价于sstream.str(std::string());
sstream.clear(); // 清除eofbit标志位
// 插入bool值
sstream << true; // 转换为int类型
sstream >> second;
cout << second << endl;
三、字符串的拼接
stringstream 中存放多个字符串,实现多个字符串拼接
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
stringstream sstream;
// 将多个字符串放入 sstream 中
cout << "开始拼接" << endl;
sstream << "first" << " " << "string,";
sstream << " second string";
cout << "最后的结果 is: " << sstream.str() << endl;
cout << "清空 sstream" << endl;
sstream.str("");
sstream << "third string";
cout << "After clear, 最后的结果 is: " << sstream.str() << endl
return 0;
}
四、实现任意类型的转换
示例代码,介绍将 string 类型转换为 int 类型过程。
#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
template<typename out_type, typename in_value>
out_type convert(const in_value & t) {
stringstream stream;
stream << t;//向流中传值
out_type result;//这里存储转换结果
stream >> result;//向result中写入值
return result;
}
int main() {
string str = "1 23 # 4";
stringstream ss;
ss << str; // 输入流
while (ss >> str) { // 输出流
cout <<"原字符串"<< str << endl;
int val = convert<int>(str);
cout << "转化后的值" << val << endl;
}
return 0;
}
参考: