stringstream,ostringstream,stringstream

istringstream的功能:string型到 int,double,float型的转换

描述:从流中提取数据,支持 >> 操作

这里字符串可以包括多个单词,单词之间使用空格分开

  1. istringstream的构造函数原形:  
  2. istringstream::istringstream(string str);  
      istringstream istr(

"1 56.7");  

      istr.str(

"1 56.7");//把字符串"1 56.7"存入字符串流中   

#include<iostream>
#include <sstream>
#include<string>
using namespace std;
int main()
{
  istringstream istr;
  string A;
  A="1 321.7";
  istr.str(A);
  //上述两个过程可以简单写成 istringstream istr("1 56.7");
  cout << istr.str()<<endl;
  int a  ;
  float b;
  istr>>a;
  cout<<a<<endl;
  istr>>b;
  cout<<b<<endl;
  system("pause");
  return 0;
}

ostringstream的功能:int double 型等转化为字符串

#include<iostream>
#include <sstream>
#include<string>
using namespace std;
int main()
{
  int a,b;
  string Str1,Str2;
  string Input="abc 123 bcd 456 sss 999";
  //ostringstream 对象用来进行格式化的输出,可以方便的将各种类型转换为string类型
  //ostringstream 只支持<<操作符
  //----------------------格式化输出---------------------------
  ostringstream oss;
  oss<<3.14;
  oss<<" ";
  oss<<"abc";
  oss<<55555555;
  oss<<endl;
  cout<<oss.str();
  system("pause");
  //-----------------double型转化为字符串---------------------
  oss.str("");//每次使用前清空,oss.clear()并不能清空内存
  oss<<3.1234234234;
  Str2=oss.str();
  cout<<Str2<<endl;
  system("pause");
  //-----------------int型转化为字符串---------------------
  oss.str("");//每次使用前清空,oss.clear()并不能清空内存
  oss<<1234567;
  Str2=oss.str();
  cout<<Str2<<endl;
  system("pause");
  //--------------------------------------------------------
  return 0;
}

stringstream的功能:1)string与各种内置类型数据之间的转换

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  stringstream sstr;
  //--------int转string-----------
  int a=100;
  string str;
  sstr<<a;
  sstr>>str;
  cout<<str<<endl;
  //--------string转char[]--------
  sstr.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。
  string name = "colinguan";
  char cname[200];
  sstr<<name;
  sstr>>cname;
  cout<<cname;
  system("pause");
}

stringstream的功能:2)通过put()或者左移操作符可以不断向ostr插入单个字符或者是字符串,通过str()函数返回增长过后的完整字符串数据,但值 得注意的一点是,

当构造的时候对象内已经存在字符串数据的时候,那么增长操作的时候不会从结尾开始增加,而是修改原有数据,超出的部分增长。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  stringstream ostr("ccccccccc");
  ostr.put('d');
  ostr.put('e');
  ostr<<"fg";
  string gstr = ostr.str();
  cout<<gstr<<endl;
  char a;
  ostr>>a;
  cout<<a ;
  system("pause");
  return 0;
}

附加一个学习链接,较详细:https://www.cnblogs.com/gamesky/archive/2013/01/09/2852356.html

猜你喜欢

转载自www.cnblogs.com/tianzeng/p/9038810.html