我是靠谱客的博主 俊逸大雁,这篇文章主要介绍C++ sstream 中处理字符串,现在分享给大家,希望可以做个参考。

C++引入ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含<sstream>这个头文件。

istringstream的构造函数原形如下:
istringstream::istringstream(string str);
它的作用是从string对象str中读取字符,stringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。

下面我们分离以空格为界限,分割一个字符串。

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream> #include<sstream> #include<string> int main() { std::string str = "I am coding ..."; std::istringstream is(str); do { std::string substr; is>>substr; std::cout << substr << std::endl; } while (is); return 0; }

程序输出

I

am 

coding

...

另外用vector也可以实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector> #include<iostream> #include <string> #include <sstream> using namespace std; int main() { string str("I am coding ..."); string buf; stringstream ss(str); vector<string> vec; while (ss >> buf) vec.push_back(buf); for (vector<string>::iterator iter = vec.begin(); iter != vec.end(); ++iter) { cout << *iter << endl; } return 0; }

补充知识点,自己积累学习

在类型转换中使用模板

你可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。例如,需要将各种数字值,如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝:

复制代码
1
2
3
4
5
6
7
8
9
template<class T> void to_string(string & result,const T& t) { ostringstream oss;//创建一个流 oss<<t;//把值传递如流中 result=oss.str();//获取转换后的字符转并将其写入result }


这样,你就可以轻松地将多种数值转换成字符串了:

to_string(s1,10.5);//double到string

to_string(s2,123);//int到string

to_string(s3,true);//bool到string

可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
template<class out_type,class in_value> out_type convert(const in_value & t) { stringstream stream; stream<<t;//向流中传值 out_type result;//这里存储转换结果 stream>>result;//向result中写入值 return result; }

这样使用convert():

double d;

string salary;

string s=”12.56”;

d=convert<double>(s);//d等于12.56

salary=convert<string>(9000.0);//salary等于”9000”

转载于:https://www.cnblogs.com/Forever-Kenlen-Ja/p/4946329.html

最后

以上就是俊逸大雁最近收集整理的关于C++ sstream 中处理字符串的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部