C++ istringstream、ostringstream、stringstream类用法详解


0 概述

C++引入了ostringstream、istringstream、stringstream这三个类,头文件<sstream>

1 istringstream

istringstream类执行C++风格的串流的输入操作。

  • 定义类型:typedef basic_istringstream<char> istringstream;
  • 继承关系:

在这里插入图片描述

  • 示例代码:
     string s = "I come from china";
     istringstream is(s);
     cout << s << endl;
     while (is >> s)
          cout << s << endl;
  • 执行结果:

在这里插入图片描述

2 ostringstream

ostringstream类执行C风格的串流的输出操作。

  • 定义类型:typedef basic_ostringstream<char> ostringstream;
  • 继承关系:

在这里插入图片描述

  • 示例代码:
     double pi = 3.141592653589793;
     ostringstream s1;
     s1.setf(ios::fixed); //显示小数
     s1.precision(10);  //10位精度
     s1 << "pi:" << pi;
     string show = s1.str();
     cout << "show:" << show << endl;
  • 执行结果:

在这里插入图片描述

3 stringstream

strstream类支持C风格的串流的输入输出操作。

  • 定义类型:typedef basic_stringstream<char> stringstream;
  • 继承关系:

在这里插入图片描述

  • 示例代码:
     double pi = 3.141592653589793;
     stringstream s1;
     s1.setf(ios::fixed); //显示小数
     s1.precision(10);
     s1 << "pi:" << pi;
     string show = s1.str();
     cout << "show:" << show << endl;
     string s = "I come from china";
     stringstream is(s);
     cout << s << endl;
     while (is >> s)
          cout << s << endl;
  • 执行结果:

在这里插入图片描述

4 类型转换

类型转换过程

// 字符转数字
ss << string("15");
int num;
ss >> num;

// 如果多次使用ss进行转换,需使用clear()函数对内容清空
ss.clear();

// 数字转字符
ss << 67;
string str;
ss >> str;

5 reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i胡说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值