C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C++中stringstream的用法和实例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

之前在leetcode中进行String和int的转化时使用过iStringstream,现在大致总结一下用法和测试用例。

介绍:C++引入了oStringstream、iStringstream、Stringstream这三个类,要使用他们创建对象就必须包含sstream.h头文件

iStringstream类用于执行C++风格的串流的输入操作。

oStringstream类用于执行C风格的串流的输出操作。

Stringstream类同时可以支持C风格的串流的输入输出操作。

下图详细描述了几种类之间的继承关系:

C++中stringstream的用法和实例

iStringstream是由一个String对象构造而来,从一个String对象读取字符。

oStringstream同样是有一个String对象构造而来,向一个String对象插入字符。

Stringstream则是用于C++风格的字符串的输入输出的。

代码测试:

#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; 
} 

输出

C++中stringstream的用法和实例

总结:

1)在iStringstream类中,构造字符串流时,空格会成为字符串参数的内部分界;

2)iStringstream类可以用作String与各种类型的转换途径

3)ignore函数参数:需要读取字符串的最大长度,需要忽略的字符

代码测试:

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的用法和实例全部内容了,希望大家多多支持编程小技巧~

大佬总结

以上是大佬教程为你收集整理的C++中stringstream的用法和实例全部内容,希望文章能够帮你解决C++中stringstream的用法和实例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。