sprintf sscanf 格式化字符串

2021-07-14  本文已影响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();
}


上一篇 下一篇

猜你喜欢

热点阅读