%s %*s

// 在C 语言中输出等宽度的显示我们一般采用的是在前面加数字的方法,
    printf("%30s\n", the_text);        // 右对齐输出,结果:"            this is test text!"
    printf("%-30s\n", the_text);       // 左对齐输出,结果:"this is test text!            "

    // 其实C 语言还对printf() 提供了一种动态添加的方法,也就是可以使用变量的方法来
    //         设置该宽度,这样就大大提高了等宽度输出的灵活性。

    const char text_char[]             = "char";
    const char text_char_var[]         = "m_ch_var";
    const char text_char_ptr[]         = "m_ch_ptr";
    const char text_int32[]            = "int32_t";
    const char text_int32_var[]        = "m_nvar";
    const char text_int32_ptr[]        = "m_pvar";

    printf("%s %*s%s;\n", text_char,  20 - strlen(text_char),  "", text_char_var);
    printf("%s*%*s%s;\n", text_char,  20 - strlen(text_char),  "", text_char_ptr);
    printf("%s %*s%s;\n", text_int32, 20 - strlen(text_int32), "", text_int32_var);
    printf("%s*%*s%s;\n", text_int32, 20 - strlen(text_int32), "", text_int32_ptr);
    // (13 + ...) 的结果是"std::vector<%s>" 的总字节宽度
    printf("std::vector<%s> %*s%s;\n", 
        text_char, 20 - (13 + strlen(text_char)), "", "m_vec_var");

    /*
    // 输出的结果如下:
    char                 m_ch_var;
    char*                m_ch_ptr;
    int32_t              m_nvar;
    int32_t*             m_pvar;
    std::vector<char>    m_vec_var;
    */


    // 对于字符串而言,还可以使用"%.*s" 限制输出字符串的最大长度,即:可以将"char", 限制只输出"ch",或者"cha".
    printf("%.*s, end.\n", 1, the_text);
    printf("%.*s, end.\n", 2, the_text);
    printf("%.*s, end.\n", 3, the_text);
    printf("%.*s, end.\n", 8, the_text);

    /*
    // 输出结果如下:
    t, end.
    th, end.
    thi, end.
    this is , end.
    */

    // 同时在前面再加上一个* 就跟上面的意义一样,设置输出宽度
    printf("%*.*s, end.\n", 10, 1, the_text);
    printf("%*.*s, end.\n", 10, 2, the_text);
    printf("%*.*s, end.\n", 10, 3, the_text);
    printf("%*.*s, end.\n", 10, 8, the_text);

    /*
    // 输出结果如下:
             t, end.
            th, end.
           thi, end.
      this is , end.
    */

    // 以上的方法同样可针对浮点数,特别是"%*.*lf",应该特别有用。

    return 0;

猜你喜欢

转载自blog.csdn.net/yunjie167/article/details/82989417
s
a's
今日推荐