sscanf、sprintf、stringstream常见用法

转载自:https://blog.csdn.net/jllongbell/article/details/79092891

前言:

    之前没有接触过stringstream这个类的时候,经常使用的字符串和数字转换函数就是sscanf和sprintf函数。开始的时候就以为这两个函数应经很叼了,可是毕竟是属于c的。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, ...)。做用是格式化字符串,具体功能以下所示:post

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

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

  (3)链接多个字符串。.net

int main(){ char str[256] = { 0 }; int data = 1024; //将data转换为字符串
    sprintf(str,"%d",data); //获取data的十六进制
    sprintf(str,"0x%X",data); //获取data的八进制
    sprintf(str,"0%o",data); const char *s1 = "Hello"; const char *s2 = "World"; //链接字符串s1和s2
    sprintf(str,"%s %s",s1,s2); cout<<str<<endl; return 0; } 

sscanf函数

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

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

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

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

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

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

  固然,sscanf能够支持格式串"%[]"形式的,有兴趣的能够研究一下。

int main(){ char s[15] = "123.432,432"; int n; double f1; int f2; sscanf(s, "%lf,%d%n", &f1, &f2, &n); cout<<f1<<" "<<f2<<" "<<n; return 0; } 

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

vstringstream类:

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

int main(){ string s = "1 23 # 4"; stringstream ss; ss<<s; while(ss>>s){ cout<<s<<endl; int val = convert<int>(s); cout<<val<<endl; } return 0; }

输出:1 1 23 23 # 0 4 4

相关文章
相关标签/搜索