定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。本文以 stringstream 为主,介绍流的输入和输出操作。
主要用来进行数据类型转换,由于 使用 string 对象来代替字符数组(snprintf方式),就避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。简单说,相比c库的数据类型转换而言, 更加安全、自动和直接。 cplusplus官方版本:
// swapping ostringstream objects #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::stringstream int main () { std::stringstream ss; ss << 100 << ' ' << 200; int foo,bar; ss >> foo >> bar; std::cout << "foo: " << foo << '\n'; std::cout << "bar: " << bar << '\n'; return 0; } Edit & RunOutput: foo: 100 bar: 200
下面代码增加while循环,能将str全部单词打印出来
#include <iostream> #include <sstream> using namespace std; int main() { string str = "hello world"; cout << str << endl; stringstream ss(str); //将str复制到ss string abc; while(ss >> abc) //相当于输入一个个的单词 { cout << abc <<endl; } return 0; }OUTPUT: 二、支持C风格的串流的输入输出操作
#include <iostream> #include <sstream> using namespace std; int main() { int num = 1000; string str; stringstream ss; //将str复制到ss ss << num; ss >> str; ss.clear();//使用stringstream来做转换时,最好使用完,进行ss.clear()操作 cout << str << endl; cout << str.c_str() << endl; return 0; }OUTPUT:
三、字符的拼接
本文作者:WeSiGJ
参考链接(包括但不限于): https://blog.csdn.net/liitdar/article/details/82598039 https://blog.csdn.net/weierqiuba/article/details/66473060 https://blog.csdn.net/xw20084898/article/details/21939811 http://www.cplusplus.com/reference/sstream/stringstream/stringstream/