C 代码中的对齐问题 - 打印星形图案

问题描述 投票:0回答:1

Stack Overflow 社区您好,

我目前正在开发一个 C 程序,我想根据用户输入打印带有对齐星星的星形图案。但是,我遇到了对齐问题,特别是在使用“ ”(制表符)字符时。我希望获得有关如何实现所需输出的指导。

这是我的代码的简化版本:

#include <stdio.h>

int main() {
    // Ages for 3 people
    int age1, age2, age3;

    // Getting all 3 users' ages
    for (int j = 0; j < 3; j++) {
        printf("Enter your age below: \n");
        if (j == 0) {
            scanf("%d", &age1);
        } else if (j == 1) {
            scanf("%d", &age2);
        } else {
            scanf("%d", &age3);
        }
    }

    // Printing a star with each age and a message
    for (int i = 0; i < 3; i++) {
        if (i == 0) {
            printf("John:%d***\n", age1);
        } else if (i == 1) {
            printf("Itachi:%d***\n", age2);
        } else {
            printf("Bob:%d****\n", age3);
        }
    }

    return 0;
}

我正在专门寻求有关如何使用适当对齐星星的建议。对我的方法的任何见解或更正将不胜感激。

提前感谢您的帮助

c function escaping
1个回答
0
投票

printf()
语句中使用字段宽度进行对齐。

#include <stdio.h>

int main() {
    // Ages for 3 people
    int age[3];
    char *names[] = {"John", "Itachi", "Bob"};

    // Getting all 3 users' ages
    for (int j = 0; j < 3; j++) {
        printf("Enter %s's age below: \n", names[j]);
        scanf("%d", &age[j]);
    }

    // Printing a star with each age and a message
    for (int i = 0; i < 3; i++) {
        printf("%-10s%3d***\n", names[i], age[i]);
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.