一、介绍
当我们需要在程序中使用字符串和数字数据互相转换的时候,可以使用stringstream类
- t头文件<sstream>定义了三个类:stringstream、istringstream、ostringstream,分别用来进行流的输入输出、输入和输出操作
- stringstream主要用来进行数据类型转换
- 通过"<<"将数据传递给stringstream对象;
- 通过调用stringstream类的函数str()将对象所包含的内容赋值给一个string对象;
- 可以方便的以流运算符"<<"将数值以各种数据写入stringstream对象,且不用担心越界等问题
- stringstream使用string对象来代替字符数组(snprintf方式),可以避免缓冲区溢出的风险
- 传入的参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题
二、用法
1、基础使用
使用stringstream
stringstream buf1;
buf1 << 6; //将int转换为stringstream对象
int n = 0;
buf1 >> n;
cout << "buf1.str() = " << buf1.str() << " n = " << n << '\n' << endl;
cout << "buf1.str().data() = " << buf1.str().data() << " buf1.str().size() = " << buf1.str().size() << endl;//input stream
istringstream inbuf("-10");
inbuf >> n; //可以将stringstream对象转换为int
cout << "n = " << n << endl;//output stream in append mode (C++11)
ostringstream buf2("test", ios_base::ate); //如果不设置第二个参数的话,就会变为 1est 1把第一个t给覆盖了
buf2 << '1';
cout << buf2.str() << '\n' << endl;
使用istringstream
int n;
istringstream in;
in.str("12");
in >> n;
cout << "after reading the int from \"1 2\",the int is " << n << ",str() = \"" << in.str() << "\"\n" << endl;
使用ostringstream
std::ostringstream out("12");
out << 3;
std::cout << "after writing the int '3' to output stream \"1 2\""
<< ", str() = \"" << out.str() << "\"\n";
out << 4;
std::cout << "after writing the int '4' to output stream \"1 2\""
<< ", str() = \"" << out.str() << "\"\n";ostringstream ate("12", ios_base::ate);
ate << 3;
cout << "after writing the int '3' to append stream \"1 2\""
<< ",str() = \"" << ate.str() << "\"\n" << endl;
stringstream、istringstream、ostringstream三种的使用都默认从头开始输入<<或输出>>,在输入的时候若没有传入参数ios_base::ate,则会将原来的流逐一覆盖,加入了参数则表示追加
stringstream分割字符串
string str = "I have a apple";
stringstream ss(str);
string s;
while (ss >> s) {
cout << s << endl;
}
stringstream拼接
//连续多次<<实现字符串的拼接
buf1<< "first" << " " << "string,";
buf1<< " second string";
stringstream清空
// 清空 buf1
buf1.clear(); // 清除eofbit标志位
buf1.str("") //等价于sstream.str(std::string());
stringstream数据转换
int n = 8;
char a;
buf1 << 8; //输入流
buf1 >> a; //输出流