IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    sprintf和sscanf函数

    admin发表于 2015-12-02 05:35:31
    love 0

    sprintf函数:

    函数原型:int sprintf ( char * str, const char * format, ... );

    函数功能:

    • (1)将数字变量转换为字符串。
    • (2)得到整型变量的16进制和8进制字符串。
    • (3)连接多个字符串。

    使用示例:

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

    示例程序:

    /* sprintf example */
    #include <stdio.h>
    
    int main ()
    {
      char buffer [50];
      int n, a=5, b=3;
      n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
      printf ("[%s] is a string %d chars long\n",buffer,n);
      return 0;
    }
    //OutPut : [5 plus 3 is 8] is a string 13 chars long

     

    sscanf函数:

    函数原型:int sscanf ( const char * s, const char * format, ...);

    函数功能:

    • (1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。
    • (2)取指定长度的字符串
    • (3)取到指定字符为止的字符串
    • (4)取仅包含指定字符集的字符串
    • (5)取到指定字符集为止的字符串

    格式字符:

    • (1)-: 表示范围,如:%[1-9]表示只读取1-9这几个数字 %[a-z]表示只读取a-z小写字母,类似地 %[A-Z]只读取大写字母
    • (2)^: 表示不取,如:%[^1]表示读取除'1'以外的所有字符 %[^/]表示除/以外的所有字符
    • (3),: 范围可以用","相连接 如%[1-9,a-z]表示同时取1-9数字和a-z小写字母
    • (4)原则:从第一个在指定范围内的数字开始读取,到第一个不在范围内的数字结束%s 可以看成%[] 的一个特例 %[^ ](注意^后面有一个空格!)

    使用示例:

        const char *s = "http://www.baidu.com:1234";
        char protocol[32] = { 0 };
        char host[128] = { 0 };
        char port[8] = { 0 };
        sscanf(s,"%[^:]://%[^:]:%[1-9]",protocol,host,port);
    
        printf("protocol: %s\n",protocol);
        printf("host: %s\n",host);
        printf("port: %s\n",port);

    示例程序:

    /* sscanf example */
    #include <stdio.h>
    
    int main ()
    {
      char sentence []="Rudolph is 12 years old";
      char str [20];
      int i;
    
      sscanf (sentence,"%s %*s %d",str,&i);
      printf ("%s -> %d\n",str,i);
      
      return 0;
    }
    //OutPut : Rudolph -> 12

     

    转载自:http://www.cnblogs.com/Anker/p/3351168.html 和 cplusplus.com



沪ICP备19023445号-2号
友情链接