在 C 中对齐输出值 [英] Aligning Output Values in C

查看:63
本文介绍了在 C 中对齐输出值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在开发一个需要格式化输出的程序.输出应该是对齐的,而且它是用小数字来对齐的:

So I'm working on a program which needs to format output. The output is supposed to be aligned, and it does do so with small numbers:

但是当我给出大数字时,它不再有效:

But then when I give big numbers, it no longer works:

我的代码是真的,但这里是打印主要输出的部分:

My code is really but here's the part that prints the main output:

/* The following code prints out the data */

    printf("\n\nStatistics: \n\n");
    printf("Descrip\t\tNumber:\t\tTotal:\t\tAverage:\n\n");
    printf("Normal\t\t%d\t\t%d\t\t%d\n\n",normal_counter,normal_total,normal_average);
    printf("Short\t\t%d\t\t%d\t\t%d\n\n",short_counter,short_total,short_average);
    printf("Long\t\t%d\t\t%d\t\t%d\n\n",long_counter,long_total,long_average);
    printf("Overall\t\t%d\t\t%d\t\t%d\n\n",overall_counter,overall_total,overall_average);

如何让输出对齐?

推荐答案

使用可用的 printf 格式化程序功能:

Use the available printf formatter capabilities:

$ cat t.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%-12s%-12d%-12d\n", "a", 2989, 9283019);
    printf("%-12s%-12d%-12d\n", "helloworld", 0, 1828274198);
    exit(0);
}

$ gcc -Wall t.c
$ ./a.out 
a           2989        9283019     
helloworld  0           1828274198  

如您所见,它甚至可以处理字符串,因此您可以通过这种方式对齐字段.

As you can see, it even work with strings, so you can align your fields this way.

这篇关于在 C 中对齐输出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆