当前位置:   article > 正文

stringstream常见用法_stringstream 初始化

stringstream 初始化

目录

构造函数 

输出字符串 

修改和清空字符串 

 利用 stringstream 去除字符串空格

 利用stringstream去除指定的字符

stringstream 数据库 <sstream>

构造函数 

  1. 创建一个对象,向对象输入字符串:
  1. string x="abcdefg";
  2. stringstream ss;
  3. ss<<x;

2.字符串初始化(一般用这个方便很多) 

  1. string x="abcdefg";
  2. stringstream ss(x);

输出字符串 

 调用str()函数 str()函数可以将其他类型的数据转换为字符串类型,从而方便我们输出和处理数据

cout<<ss.str()<<endl;

修改和清空字符串 

  1. #include<iostream>
  2. #include<sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. string x="abcdefgh";
  7. //初始化
  8. stringstream ss(x);
  9. cout<<ss.str()<<endl;
  10. //修改字符串
  11. ss.str("1234565");
  12. cout<<ss.str()<<endl;
  13. //清空字符串
  14. //ss.clear();
  15. ss.str(" ");
  16. cout<<ss.str()<<endl;
  17. cout<<"0"<<endl;
  18. return 0;
  19. }

 

 利用 stringstream 去除字符串空格

  1. #include<iostream>
  2. #include<sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. string x="a b c d efg h j";
  7. stringstream ss(x);
  8. string s;
  9. while(ss>>s)
  10. {
  11. cout<<s<<endl;
  12. }
  13. return 0;
  14. }

 

 利用stringstream去除指定的字符

 借用getline()函数

  1. #include<iostream>
  2. #include<sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. string x="a, b, c,d,efg,h,j";
  7. stringstream ss(x);
  8. string s;
  9. while(getline(ss,s,','))
  10. {
  11. cout<<s<<endl;
  12. }
  13. return 0;
  14. }

 

从字符串到数字

  1. #include<iostream>
  2. #include<sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. string x="12345678";
  7. stringstream ss(x);
  8. int p;
  9. ss>>p;//就想象成读入给p p就有值了(从ss中提取数据 输入到x中)
  10. cout<<p<<endl;
  11. cout<<p/2<<endl;
  12. return 0;
  13. }

 

>>是流提取符  <<是流插入符

  1. #include<iostream>
  2. #include<sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. string x="12 34 56 78";
  7. stringstream ss(x);
  8. int p;
  9. while(ss>>p)
  10. {
  11. cout<<p<<endl;
  12. cout<<"*** "<<p/2<<endl;
  13. }
  14. return 0;
  15. }

 

从数字到字符串

  1. #include<iostream>
  2. #include<cstring>
  3. #include<sstream>
  4. #include<algorithm>
  5. using namespace std;
  6. int main()
  7. {
  8. stringstream str;
  9. string sstr;
  10. int x=99;
  11. str<<x;//<<流插入 将x中的数据插入到str中
  12. cout<<str.str();//str>>sstr
  13. return 0;
  14. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号