c++中好用的stringstream

来源:互联网 发布:xp ie8 淘宝 版本过低 编辑:程序博客网 时间:2024/06/05 20:57

stringstream是c++的模板库<sstream>的一个类,用于输入输出操作,此外,还有istringstream类用于输入操作,ostringstream类用于输出操作。

stringstream中有两个常用的函数,即clear()和str()。

str()       //用于将字符串流stringstream中的数据转换为字符串类型str("abc")  //以字符串为类型的参数,用于覆盖其已有的数据,特别的str("")即为字符串清零


stringstream通常可用于作数据切分或类型转换,下面以栗子分别介绍。


1. 数据切分

#include <iostream>#include <sstream>#include <string> using namespace std;int main(){string s;stringstream ss;int x, y;string z;getline(cin, s);ss.clear();ss.str(s);ss >> x >> y >> z;cout<<x<<endl;cout<<y<<endl;cout<<z<<endl;}


2. 类型转换

#include <iostream>#include <sstream>#include <string> using namespace std;template<class T>void to_string(string& result, const T& t){ostringstream oss;  //创建一个流oss << t;           //把值传递到流中result = oss.str(); //获取转换后的字符 将其写入result }int main(){string s1,s2,s3;to_string(s1, 123);    //将int类型转换成string to_string(s2, 5.26);   //将double类型转换成string to_string(s3, true);   //将bool类型转换成string cout<<s1<<endl;cout<<s2<<endl;cout<<s3<<endl;}



note: 如果多次转换中使用同一个stringstream,需要在每次转换前使用clear()方法,以提高效率。

#include <sstream>#include <iostream>int main(){    std::stringstream stream;    int first, second;    stream<< "456"; //插入字符串    stream >> first; //转换成int    std::cout << first << std::endl;    stream.clear(); //在进行多次转换前,必须清除stream    stream << true; //插入bool值    stream >> second; //提取出int    std::cout << second << std::endl;} 


原创粉丝点击