前言:

 以前没有接触过stringstream这个类的时候,常用的字符串和数字转换函数就是sscanf和sprintf函数。开始的时候就觉得这两个函数应经很叼了,但是毕竟是属于c的。c++中引入了流的概念,通过流来实现字符串和数字的转换方便多了。在这里,总结之前的,并介绍新学的。

常见格式串:  

  %% 印出百分比符号,不转换。
  %c 整数转成对应的 ASCII 字元。
  %d 整数转成十进位。
  %f 倍精确度数字转成浮点数。
  %o 整数转成八进位。
  %s 整数转成字符串。
  %x 整数转成小写十六进位。
  %X 整数转成大写十六进位。
  %n sscanf(str, "%d%n", &dig, &n),%n表示一共转换了多少位的字符

sprintf函数

   sprintf函数原型为 int sprintf(char *str, const char *format, ...)。作用是格式化字符串,具体功能如下所示:

  (1)将数字变量转换为字符串。

  (2)得到整型变量的16进制和8进制字符串。

  (3)连接多个字符串。

  1. int main(){
  2. char str[] = { };
  3. int data = ;
  4. //将data转换为字符串
  5. sprintf(str,"%d",data);
  6. //获取data的十六进制
  7. sprintf(str,"0x%X",data);
  8. //获取data的八进制
  9. sprintf(str,"0%o",data);
  10. const char *s1 = "Hello";
  11. const char *s2 = "World";
  12. //连接字符串s1和s2
  13. sprintf(str,"%s %s",s1,s2);
  14. cout<<str<<endl;
  15. return ;
  16. }

sscanf函数

  sscanf函数原型为int sscanf(const char *str, const char *format, ...)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:

  (1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。

  (2)取指定长度的字符串

  (3)取到指定字符为止的字符串

  (4)取仅包含指定字符集的字符串

  (5)取到指定字符集为止的字符串

  当然,sscanf可以支持格式串"%[]"形式的,有兴趣的可以研究一下。

  1. int main(){
  2. char s[] = "123.432,432";
  3. int n;
  4. double f1;
  5. int f2;
  6. sscanf(s, "%lf,%d%n", &f1, &f2, &n);
  7. cout<<f1<<" "<<f2<<" "<<n;
  8. return ;
  9. }

  输出结果:123.432 432 11, 即一共转换了11位的字符。

stringstream类:

  <sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。

  1.stringstream::str(); returns a string object with a copy of the current contents of the stream.

  2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.

  3.stringstream清空,stringstream s; s.str("");

  4.实现任意类型的转换

    template<typename out_type, typename in_value>
    out_type convert(const in_value & t){
      stringstream stream;
      stream<<t;//向流中传值
      out_type result;//这里存储转换结果
      stream>>result;//向result中写入值
      return result;
    }

  1. int main(){
  2. string s = "1 23 # 4";
  3. stringstream ss;
  4. ss<<s;
  5. while(ss>>s){
  6. cout<<s<<endl;
  7. int val = convert<int>(s);
  8. cout<<val<<endl;
  9. }
  10. return ;
  11. }

  输出:1 1 23 23 # 0 4 4

  

  顺便说一下,今天做题的时候也用到了stringstream这个类,是二叉树的序列化和反序列化。

  题目链接:http://www.lintcode.com/zh-cn/problem/binary-tree-serialization/

二叉树的序列化和反序列化

  设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

思路:

  通过先序遍历建立二叉树的序列化,其中空子树用'#'来表示。反序列化的时候呢,遇到'#'就停止递归构造。另外序列化的时候是将整数通过stringstream转换成字符串,反序列化是将字符串通过stringstream转换成整数。

  1. /**
  2. * Definition of TreeNode:
  3. * class TreeNode {
  4. * public:
  5. * int val;
  6. * TreeNode *left, *right;
  7. * TreeNode(int val) {
  8. * this->val = val;
  9. * this->left = this->right = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * This method will be invoked first, you should design your own algorithm
  17. * to serialize a binary tree which denote by a root node to a string which
  18. * can be easily deserialized by your own "deserialize" method later.
  19. */
  20. bool first;
  21.  
  22. template<typename out_type, typename in_value>
  23. out_type convert(const in_value & t){
  24. stringstream stream;
  25. stream<<t;//向流中传值
  26. out_type result;//这里存储转换结果
  27. stream>>result;//向result中写入值
  28. return result;
  29. }
  30.  
  31. void pre_order(TreeNode *root, string &s){
  32. if(root){
  33. string tmp = convert<string>(root->val);
  34. if(!first)
  35. s+= " "+tmp;
  36. else {
  37. first = false;
  38. s+=tmp;
  39. }
  40. pre_order(root->left, s);
  41. pre_order(root->right, s);
  42. } else {
  43. if(first)
  44. s+='#';
  45. else {
  46. first = false;
  47. s+=" #";
  48. }
  49. }
  50. }
  51. string serialize(TreeNode *root) {
  52. // write your code here
  53. string s="";
  54. first = true;
  55. pre_order(root, s);//先序实现序列化
  56. return s;
  57. }
  58.  
  59. stringstream ss;
  60. void buildT(TreeNode * &T){
  61. string s;
  62. ss>>s;
  63. if(s == "#") return ;
  64. int val = convert<int>(s);
  65. T = new TreeNode(val);
  66. buildT(T->left);
  67. buildT(T->right);
  68. }
  69.  
  70. /**
  71. * This method will be invoked second, the argument data is what exactly
  72. * you serialized at method "serialize", that means the data is not given by
  73. * system, it's given by your own serialize method. So the format of data is
  74. * designed by yourself, and deserialize it here as you serialize it in
  75. * "serialize" method.
  76. */
  77. TreeNode *deserialize(string data) {
  78. // write your code here
  79. TreeNode *T = NULL;
  80. ss.str("");
  81. ss<<data;
  82. buildT(T);
  83. return T;
  84. }
  85. };

c++ stringstream(老好用了)的更多相关文章

  1. stringstream的用法【转】

    [本文来自]http://www.builder.com.cn/2003/0304/83250.shtmlhttp://www.cppblog.com/alantop/archive/2007/07/ ...

  2. C++ stringstream介绍,使用方法与例子

    From: http://www.usidcbbs.com/read-htm-tid-1898.html C++引入了ostringstream.istringstream.stringstream这 ...

  3. [转]stringstream的用法

    使用stringstream对象简化类型转换C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能,即单纯性.类型安全和可扩展性.在本文中, ...

  4. 转:stringstream的用法

    [本文来自]http://www.builder.com.cn/2003/0304/83250.shtmlhttp://www.cppblog.com/alantop/archive/2007/07/ ...

  5. stringstream

    C++引入了ostringstream.istringstream.stringstream这三个类,要使用他们创建对象就必须包含sstream.h头文件. istringstream类用于执行C++ ...

  6. [转]string和stringstream用法总结

    转自:http://blog.csdn.net/xw20084898/article/details/21939811 作者:xw20084898 一.string string 是 C++ 提供的字 ...

  7. 使用stringstream类

    当需要格式化int类型为字符串时,可以使用这个类, 需要包含这个文件头: #include <sstream> 然后这样使用: //打开保存进度的RPG文件. std::stringstr ...

  8. 强大的stringstream

    [本文来自]http://www.builder.com.cn/2003/0304/83250.shtmlhttp://www.cppblog.com/alantop/archive/2007/07/ ...

  9. C++ stringstream的用法

    Created at    stringstream的用法 使用stringstream对象简化类型转换 C++标准库中的<sstream>提供了比ANSI C的<stdio.h&g ...

随机推荐

  1. Vim 插入递增列

    <C-a> ++1 <C-x> --1     安装Plugin 'terryma/vim-multiple-cursors'后 <C-v> 选所有数字 <C ...

  2. xampp常见安装失败问题

    遇到这两个错误后不管它,继续安装.完成后下载Microsoft Visual C++ 2008 Redistributable Package (x86),可以到这里下载:Microsoft Visu ...

  3. MAC系统设置SSX教程与下载

    http://ss.hongxingchajian.com MAC系统设置SSX教程与下载 1.下载客户端并安装,装完后打开 链接: http://pan.baidu.com/s/1o7ypp5g 密 ...

  4. Erlang error handling

    Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...

  5. Java 用LinkdeList实现52张扑克牌

    用LinkdeList实现52张扑克牌(不含大小王)的洗牌功能.提示:花色 ,和数字分别用数组存储. import java.util.LinkedList; import java.util.Ran ...

  6. HDU1401 BFS

    Solitaire Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total S ...

  7. phone 调试三种工具

    1. Phonegap桌面开发工具 Phonegap Desktop-App与 手机客户端调试工具PhoneGap Developer App 此工具方便.快捷.自动.可以在真机中查看 无法设置断点. ...

  8. C++ 小知识积累

    (1)setw和setfill函数 #include<iomanip> 代码: #include<iostream> #include<iomanip> using ...

  9. 安卓学习之--UI控件用法 单选 按钮 下拉框

    1.单选 .RadioGroup 可将各自不同的RadioButton ,设限于同一个Radio 按钮组,同一个RadioGroup 组里的按钮,只能做出单一选择(单选题). <RadioGro ...

  10. RxJava 备注

    RxJava是一个采用观察者模式的异步框架,本文给出几个基本的使用例子. 1.配置依赖: compile 'io.reactivex:rxjava:1.0.14' compile 'io.reacti ...