C language-printf prints the difference between %*s, %.*s and %-.*s

1. Introduction

        In normal use, printf is often used for printing , and the longest used method is printf("%s", string) for printing. But there is a problem, if the end of the string is not 0. Then printf will continue to print until it encounters 0 . There is a risk of memory overflow . Obviously, this is not what was expected. Therefore, at this time, %*s needs to come out to help.

2. Function introduction

        printf("%s",string)

        Print a string and stop when 0 is encountered .

        printf("%*s",10,string)或printf("%10s",string)

        Print the string, occupying at least 10 bytes. If not enough , add 0on the left , if more than 10, according to the actual length .

        printf("%.*s",10,string)或printf("%.10s",string)

        Print string, up to 10 bytes. If it is not enough , it will be according to the actual length , if it exceeds 10, only 10 will be printed .

        

        printf("%-*s",10,string)或printf("%-10s",string)

        Print the character string, occupying at least 10 bytes, if not enough, add 0 on the right , if more than 10, according to the actual length.

        Note: %-s just changes the direction of the alignment . Normally, it is right-aligned, and after adding "-", it is left-aligned.

3. Example

        See the following code, where we print in three ways: %*s, %.*s and %-*s respectively.

    char *string1 = "this is a test string";

    uint8_t len = strlen(string1);

    printf("len:%d,%s\r\n",len,string1);
    printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n");
    printf("%15s|\r\n%*s|\r\n%-30s|\r\n",string1,30,string1,string1);
    printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n");
    printf("%.15s|\r\n%.*s|\r\n%-.30s|\r\n",string1,30,string1,string1);
    printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n");

        Look at the result:

        

         As you can see, the length of the string to be printed is 21 bytes . %*s print, if the length to be printed is greater than the set length, the actual length will be printed . For %.*s printing, if the length to be printed is greater than the set length, only the set length will be printed . And %-*s just changes right alignment to left alignment .

Guess you like

Origin blog.csdn.net/qq_26226375/article/details/130811105