Practice_sscanf_sprintf

// Practice_sscanf_sprintf.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    int i;
    unsigned int j;
    char input[ ] = "10 0x1b aaaaaaaa bbbbbbbb";
    char s1[9];//数组大小是字符串长度+1,1为结束符
    char s2[6];
    //sscanf(input,"%d %x %5[a-z]s %s", &i, &j, s1, s2);
    sscanf(input,"%d %x  %s %5[a-z]s", &i, &j, s1, s2);//%5[a-z]s有截取的必须放在最后,否则不能得到预期
    printf("%d 0x%x %s %s
", i, j, s1, s2);

    char str[512] = "";
    sscanf("123456 ", "%4s", str);
    printf("str=%s
", str);// 1234

    //取到指定字符为止的字符串,此处为空格
    //^ 表示不取,如:%[^1]表示读取除'1'以外的所有字符 %[^/]表示除/以外的所有字符
    sscanf("123456 abcdedf", "%[^ ]s", str);
    printf("str=%s
", str);// 123456

    //取仅包含指定字符集的字符串。如在下例中,取仅包含1到9和小写字母的字符串。
    sscanf("123456abcdedfBCDEF", "%[1-9,a-z]s", str);
    printf("str=%s
", str);// 123456abcdedf
    sscanf("123456BCDEFabcdedf", "%[1-9,a-z]s", str);//遇到不属于[1-9,a-z]就停止
    printf("str=%s
", str);// 123456

    //取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。
    sscanf("123456abcdedfBCDEF", "%[^A-Z]s", str);
    printf("str=%s
", str);//123456abcdedf
    sscanf("123456BCDEFabcdedf", "%[^A-Z]s", str);
    printf("str=%s
", str);//123456

    /*************************sprintf************************************/

    char cs[100];
    int k=255;
    sprintf(cs,"%d",k);
    printf("cs is: %s
", cs);

    //sprintf将数值转为十六进制字符串
    sprintf(cs,"%x",k);
    printf("cs is: %s
", cs);

    //sprintf连接字符串
    char buf[1024];
    char a[100]="I ";
    char b[100]="love ";
    char c[100]="ACM.";
    sprintf(buf,"%s%s%s",a,b,c);
    printf("buf is: %s
", buf);

    return 0;
}

很好很强大的字符串整型值浮点数值等等转换神器。

原文地址:https://www.cnblogs.com/liuzc/p/6561926.html