您可以使用printf
字段宽度说明符截断字符串:
printf("%.5s", "abcdefgh");
> abcde
不幸的是它不适用于数字(用d
替换x
是相同的):
printf("%2d", 1234); // for 34
printf("%.2d", 1234); // for 34
printf("%-2d", 1234); // for 12
printf("%-.2d", 1234); // for 12
> 1234
是否有一种简单/平凡的方式来指定要打印的位数,即使它意味着截断数字?
MSDN特别是says that it will not happen似乎不必要地限制。 (是的,它可以通过创建字符串等来完成,但我希望有一个“printf trick”或聪明的kludge。)
就像我最好的想法一样,我躺在床上等着睡着了(当时没有什么别的事可做,而不是想想)。
使用模数!
printf("%2d\n", 1234%10); // for 4
printf("%2d\n", 1234%100); // for 34
printf("%2x\n", 1234%16); // for 2
printf("%2x\n", 1234%256); // for d2
它不是理想的,因为它不能从左边截断(例如,12
而不是34
),但它适用于主要用例。例如:
// print a decimal ruler
for (int i=0; i<36; i++)
printf("%d", i%10);
如果要从右侧截断,可以将数字转换为字符串,然后使用字符串字段宽度说明符。
"%.3s".format(1234567.toString)
Bash命令行示例:
localhost ~$ printf "%.3s\n" $(printf "%03d" 1234)
123
localhost ~$
您可以使用snprintf从右侧截断
char buf[10];
static const int WIDTH_INCL_NULL = 3;
snprintf(buf, WIDTH_INCL_NULL, "%d", 1234); // buf will contain 12
为什么不从左边?唯一的区别是使用简单的划分:
printf("%2d", 1234/100); // you get 12