You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言printf输出居中对齐 无需逐行添加%.s格式符的解决方案问询

C语言菜单批量居中打印简化方案

方案1:封装自定义打印函数(最推荐,可维护性最高)

将固定缩进、换行逻辑全部封装到独立工具函数中,后续新增菜单行仅需调用函数传入文本即可,无需重复编写格式符:

#include <stdio.h>

void print_menu(const char *content) {
    // 固定输出40个前置空格,和你原代码的%40.s效果完全一致
    printf("\n%40.s%s", "", content);
}

int main(void)
{
    print_menu("press :");
    print_menu("1.) Display all existing products:");
    print_menu("2.) Add new product details:");
    print_menu("3.) Edit a existing product:");
    print_menu("4.) Make a purchase.");
    print_menu("5.) Delete a list :");
    print_menu("6.) Display Profit/loss is sales:");
    print_menu("7.) Display all product with zero quantity");
    print_menu("8.) Display all product with highest quantity");
    print_menu("9.) Change user password.");
    print_menu("10.) Exit the program.\n");
    return 0;
}

后续如果要调整缩进宽度,只需要修改函数里的数值40即可,不需要逐行修改所有打印语句。

方案2:宏定义简化(轻量场景适用)

如果不想新增独立函数,可以用宏定义包装固定格式,代码更简洁:

#include <stdio.h>
// ##__VA_ARGS__ 兼容后续需要插入变量的打印场景
#define MENU_PRINT(content, ...) printf("\n%40.s" content, "", ##__VA_ARGS__)

int main(void)
{
    MENU_PRINT("press :");
    MENU_PRINT("1.) Display all existing products:");
    MENU_PRINT("2.) Add new product details:");
    MENU_PRINT("3.) Edit a existing product:");
    MENU_PRINT("4.) Make a purchase.");
    MENU_PRINT("5.) Delete a list :");
    MENU_PRINT("6.) Display Profit/loss is sales:");
    MENU_PRINT("7.) Display all product with zero quantity");
    MENU_PRINT("8.) Display all product with highest quantity");
    MENU_PRINT("9.) Change user password.");
    MENU_PRINT("10.) Exit the program.\n");
    return 0;
}

注:原代码中的void main不属于C标准写法,替换为int main(void) + 结尾return 0兼容性更好。


内容的提问来源于stack exchange,提问作者MrWhoseTheNoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 18:48:02