printf("%*.*s\n")
2016-06-07 21:03
246 查看
#include <stdio.h> #include <string.h> int main() { const char the_text[] = "this is test text!"; // 在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; }
相关文章推荐
- 配置Tomcat服务器数据连接池
- 如何解决JsonObject无序的问题
- Servlet&JSP (二)自定义Tag
- Windows XP下static控件文字显示为倾斜或是乱码的原因分析
- 21岁开始练字晚不晚?
- 中国快递如何健康升级?
- 不曾有练字基础的成年人,应该如何科学地练字会更有成效?
- HDU4847 Wow! Such Doge!
- Dagger2最简单注入使用
- 洛谷 【P1120】 小木棍
- MySQL数据库优化(二)——MySQL事务
- printf "%.*s"
- hdu 5443(线段树水)
- awk简单使用
- 羡慕写字漂亮的人,怎么样练字?
- Android之PowerManager简介
- iOSGCD总结
- hdu 1142/hrbust 1347 A Walk Through the Forest/森林中的路【SPFA+记忆化搜索】
- Leetcode 349. Intersection of Two Arrays
- 乐学成语——显示每条成语的详细信息