printf("%*s\n", 1, ""); 使用"printf();" 的格式化输出动态制定等宽度输出。
1 #include <stdio.h> 2 #include <string.h> 3 4 int main() 5 { 6 const char the_text[] = "this is test text!"; 7 8 // 在C 语言中输出等宽度的显示我们一般采用的是在前面加数字的方法, 9 printf("%30s\n", the_text); // 右对齐输出,结果:" this is test text!" 10 printf("%-30s\n", the_text); // 左对齐输出,结果:"this is test text! " 11 12 // 其实C 语言还对printf() 提供了一种动态添加的方法,也就是可以使用变量的方法来 13 // 设置该宽度,这样就大大提高了等宽度输出的灵活性。 14 15 const char text_char[] = "char"; 16 const char text_char_var[] = "m_ch_var"; 17 const char text_char_ptr[] = "m_ch_ptr"; 18 const char text_int32[] = "int32_t"; 19 const char text_int32_var[] = "m_nvar"; 20 const char text_int32_ptr[] = "m_pvar"; 21 22 printf("%s %*s%s;\n", text_char, 20 - strlen(text_char), "", text_char_var); 23 printf("%s*%*s%s;\n", text_char, 20 - strlen(text_char), "", text_char_ptr); 24 printf("%s %*s%s;\n", text_int32, 20 - strlen(text_int32), "", text_int32_var); 25 printf("%s*%*s%s;\n", text_int32, 20 - strlen(text_int32), "", text_int32_ptr); 26 // (13 + ...) 的结果是"std::vector<%s>" 的总字节宽度 27 printf("std::vector<%s> %*s%s;\n", 28 text_char, 20 - (13 + strlen(text_char)), "", "m_vec_var"); 29 30 /* 31 // 输出的结果如下: 32 char m_ch_var; 33 char* m_ch_ptr; 34 int32_t m_nvar; 35 int32_t* m_pvar; 36 std::vector<char> m_vec_var; 37 */ 38 39 40 // 对于字符串而言,还可以使用"%.*s" 限制输出字符串的最大长度,即:可以将"char", 限制只输出"ch",或者"cha". 41 printf("%.*s, end.\n", 1, the_text); 42 printf("%.*s, end.\n", 2, the_text); 43 printf("%.*s, end.\n", 3, the_text); 44 printf("%.*s, end.\n", 8, the_text); 45 46 /* 47 // 输出结果如下: 48 t, end. 49 th, end. 50 thi, end. 51 this is , end. 52 */ 53 54 // 同时在前面再加上一个* 就跟上面的意义一样,设置输出宽度 55 printf("%*.*s, end.\n", 10, 1, the_text); 56 printf("%*.*s, end.\n", 10, 2, the_text); 57 printf("%*.*s, end.\n", 10, 3, the_text); 58 printf("%*.*s, end.\n", 10, 8, the_text); 59 60 /* 61 // 输出结果如下: 62 t, end. 63 th, end. 64 thi, end. 65 this is , end. 66 */ 67 68 // 以上的方法同样可针对浮点数,特别是"%*.*lf",应该特别有用。 69 70 return 0; 71 }