C++语法基础--标准IO库--字符串流

1.标准库定义的三中类型的字符串流(#include<sstream>)
  istringstream,ostringstream,stringstream
  
  *stringstream:
     构造函数:
          explicit stringstream (ios_base::openmode which = ios_base::in | ios_base::out);


           explicit stringstream (const string& str,
                       ios_base::openmode which = ios_base::in | ios_base::out);

      方法:
          string str() const;
          void str (const string& s)



   eg:
      string str("hello");       
      stringstream strm;          
 //创建自由的stringstream对象
      stringstream strm1(str);      //创建存储str的副本的stringstream对象
      strm1.str();                  //返回strm1中存储的string类型对象
      strm.str(str);               //将string类型的str复制给strm,返回void


  应用一:将一句话拆分成单词
    int main()
 { 
   string line,word;
   getline(cin,line);          
 //输入hello how are you
   istringstream strm(line);      //创建存储line的副本的stringstream对象
   int count=0;
   while(strm>>word)
   {
   cout<<++count<<":"<<word<<'\t';    //1: hello  2:how   3:are  4:you
   }
   return 0;
 
 }


  
 应用二:格式转换/格式化
  int main()
{
   string total,wipe;
   int val1=1,val2=2,val3=0,val4=0;
   ostringstream write;
   write<<"val1: "<<val1<<ends<<"val2: "<<val2<<endl; 
 //将表达式转为字符串(格式转换)
   total=write.str();
   cout<<total<<endl;    //输出val1: 1 val2:2
   istringstream read(total);
   read>>wipe>>val3>>wipe>>val4;     //将字符串的内容提取出来,注意提取时需对应写入时的顺序(格式化)
   cout<<"val3: "<<val3<<ends<<"val4: "<<val4<<endl; //输出val3: 1 val4:2
   return 0;
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值