美文网首页
sprintf sscanf 格式化字符串

sprintf sscanf 格式化字符串

作者: 李永开 | 来源:发表于2021-07-14 16:20 被阅读0次

一. sprintf 格式化输出

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>



int main(int argc, const char * argv[]) {
    
    char buffer[1024] = {0};
    
    sprintf(buffer, "hello_%s", "lyk");

    printf("%s\n", buffer);
    
    return 0;
    
    //hello_lyk
}

二. sscanf 格式化输出

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>


// %*s %*d 跳过数据
void test1(){
    char *s = "12345abcde";
    char buffer[1024] = {0};
    sscanf(s, "%*d%s", buffer);
    printf("%s\n", buffer);
    
    //输出:abcde
    // %*d 忽略是数字的部分
}

// %[width]s
void test2(){
    char *s = "12345abcde";
    char buffer[1024] = {0};
    sscanf(s, "%3s", buffer);
    printf("%s\n", buffer);
    
    //输出:123
}

// %[a-z]
void test3(){
    /*
    char *s = "12345abcde";
    char buffer[1024] = {0};
    sscanf(s, "%[a-z]", buffer);
    printf("%s\n", buffer);
    //输出:空
     */
    
    
    char *s = "abcde12345";
    char buffer[1024] = {0};
    sscanf(s, "%[a-z]", buffer);
    printf("%s\n", buffer);
    //输出:abcde
}

int main(int argc, const char * argv[]) {
  
//    test1();
//    test2();
    test3();
}


相关文章

网友评论

      本文标题:sprintf sscanf 格式化字符串

      本文链接:https://www.haomeiwen.com/subject/wcvcpltx.html