如何使用printf将表格数据左对齐?

发布于 2025-01-12 03:39:31 字数 707 浏览 0 评论 0原文

假设我们想要在 C 语言中使用 printf 显示以表格方式对齐的不同值。

我们可以这样做:

#include <stdio.h>
int main()
{
    char strings[5][10] = {"Test1","Test2","Test3","Test4","Test5"};
    int ints[5] = {1,2,3,4,5};
    float floats[5] = {1.5,2.5,3.5,4.5,5.5};
    int i;
    printf("%10s%10s%10s\n","Strings","Ints","Floats");
    for(i=0;i<5;i++){
        printf("%10s%10d%10.2f\n",strings[i],ints[i],floats[i]);
    }
    return 0;
}

在这个例子中,我们有 5 个字符串、5 个整数和 5 个浮点数。在每一行,我想将它们对齐显示。这段代码就是这样做的。但是,数据是右对齐的。我们可以在下图中看到结果:

在此处输入图像描述

我怎样才能做这样的事情,但将数据向左对齐?

Let us suppose that we want to display different values aligned in a tabular way, in C, using printf.

We can do something like this:

#include <stdio.h>
int main()
{
    char strings[5][10] = {"Test1","Test2","Test3","Test4","Test5"};
    int ints[5] = {1,2,3,4,5};
    float floats[5] = {1.5,2.5,3.5,4.5,5.5};
    int i;
    printf("%10s%10s%10s\n","Strings","Ints","Floats");
    for(i=0;i<5;i++){
        printf("%10s%10d%10.2f\n",strings[i],ints[i],floats[i]);
    }
    return 0;
}

In this example, we have 5 strings, 5 ints, and 5 floats. At each line, I would like to display them aligned. This piece of code does this. However, the data is aligned to the right. We can see the result in the following image:

enter image description here

How can I do something like this, but aligning the data to the left?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风月客 2025-01-19 03:39:31

在格式字符串中使用标志“-”,如

    printf( "%-10s%-10s%-10s\n", "Strings", "Ints", "Floats" );
    for (i = 0; i < 5; i++) {
        printf( "%-10s%-10d%-10.2f\n", strings[i], ints[i], floats[i] );
    }

来自 C 标准 (7.21.6.1 fprintf 函数)

6 标志字符及其含义是:

'-' 转换结果在字段内左对齐。 (如果未指定该标志,则右对齐。)

Use the flag '-' in the format strings like

    printf( "%-10s%-10s%-10s\n", "Strings", "Ints", "Floats" );
    for (i = 0; i < 5; i++) {
        printf( "%-10s%-10d%-10.2f\n", strings[i], ints[i], floats[i] );
    }

From the C Standard (7.21.6.1 The fprintf function)

6 The flag characters and their meanings are:

'-' The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文