之前在leetcode中进行string和int的转化时使用过istringstream,现在大致总结一下用法和测试用例。
介绍:C++引入了ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含sstream.h头文件。
istringstream类用于执行C++风格的串流的输入操作。
ostringstream类用于执行C风格的串流的输出操作。
stringstream类同时可以支持C风格的串流的输入输出操作。
下图详细描述了几种类之间的继承关系:
istringstream是由一个string对象构造而来,从一个string对象读取字符。
ostringstream同样是有一个string对象构造而来,向一个string对象插入字符。
stringstream则是用于C++风格的字符串的输入输出的。
代码测试:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#include<iostream>
#include <sstream>
using namespace std;<pre name="code" class="cpp">int main(){
string test = "-123 9.87 welcome to, 989, test!";
istringstream iss;//istringstream提供读 string 的功能
iss.str(test);//将 string 类型的 test 复制给 iss,返回 void
string s;
cout << "按照空格读取字符串:" << endl;
while (iss >> s){
cout << s << endl;//按空格读取string
}
cout << "*********************" << endl;
istringstream strm(test);
//创建存储 test 的副本的 stringstream 对象
int i;
float f;
char c;
char buff[1024];
strm >> i;
cout <<"读取int类型:"<< i << endl;
strm >> f;
cout <<"读取float类型:"<<f << endl;
strm >> c;
cout <<"读取char类型:"<< c << endl;
strm >> buff;
cout <<"读取buffer类型:"<< buff << endl;
strm.ignore(100, ',');
int j;
strm >> j;
cout <<"忽略‘,'读取int类型:"<< j << endl;
system("pause");
return 0;
}
|
输出:
总结:
1)在istringstream类中,构造字符串流时,空格会成为字符串参数的内部分界;
2)istringstream类可以用作string与各种类型的转换途径
3)ignore函数参数:需要读取字符串的最大长度,需要忽略的字符
代码测试:
?
|
1
2
3
4
5
6
7
8
9
10
|
int main(){
ostringstream out;
out.put('t');//插入字符
out.put('e');
out << "st";
string res = out.str();//提取字符串;
cout << res << endl;
system("pause");
return 0;
}
|
输出:test字符串;
注:如果一开始初始化ostringstream,例如ostringstream out("test"),那么之后put或者<<时的字符串会覆盖原来的字符,超过的部分在原始基础上增加。
stringstream同理,三类都可以用来字符串和不同类型转换。
以上就是小编为大家带来的C++中stringstream的用法和实例全部内容了,希望大家多多支持快网idc~
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 96
-
2025-05-25 26
-
2025-05-25 76
-
2025-06-04 46
-
2025-05-27 108
热门评论



