首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印输出在c++中居中对齐的解决方案

打印输出在c++中居中对齐的解决方案
EN

Stack Overflow用户
提问于 2021-08-13 16:10:05
回答 2查看 91关注 0票数 0

我试过使用%.s,但是我不想在每一行都使用它,有什么解决方案吗?

代码语言:javascript
复制
#include<stdio.h>
void main()
{
    printf("\n %40.s press :");
    printf("\n %40.s 1.) Display all existing products:");
    printf("\n %40.s 2.) Add new product details:");
    printf("\n %40.s 3.) Edit a existing product:");
    printf("\n %40.s 4.) Make a purchase.");
    printf("\n %40.s 5.) Delete a list :");
    printf("\n %40.s 6.) Display Profit/loss is sales:");
    printf("\n %40.s 7.) Display all product with zero quantity");
    printf("\n %40.s 8.) Display all product with highest quantity");
    printf("\n %40.s 9.) Change user password.");
    printf("\n %40.s 10.) Exit the program.\n");
}

我想要像this这样的输出。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-13 17:42:04

我关注的是您在标题中提出的问题,而不是您的代码,因为您的代码做了一些非常不同的事情,并且与标题中的问题无关。

单独的printf()不能居中显示文本。您必须找出要打印的文本的长度,然后在需要对齐时打印填充空格字符。正如其他人所说,创建一个函数:

代码语言:javascript
复制
//Prints Text in the center of width, when possible
int printCenter(FILE *out, const char *str, size_t width)
{
  size_t l=strlen(str); //Find out how long the text is
  if(l<width) // only print padding chars when we can align the text
  {
    size_t p=(width-l)/2;
    //Need to convert p to a int, only do that when p is small enough
    //use UINT_MAX in #if because p is <=SIZE_MAX/2. This avoids the
    //Check when size_t and int have the same rank
    #if SIZE_MAX>UINT_MAX
    if(p>INT_MAX)
    {
      errno=ERANGE;
      return -1;
    }
    #endif
    //print the padding chars to the left
    if(fprintf(out,"%*s",(int)p,"")<0) return -1;
  }
  return fprintf(out,"%s\n",str);
}

别忘了包括正确的标题。

票数 2
EN

Stack Overflow用户

发布于 2021-08-13 17:16:28

代码语言:javascript
复制
typedef struct
{
    char *string;
    int (*handler)(const int, const char *, void *);
}menu_type;

void print_menu(int width, const menu_type *menu)
{
    int pos = 1;
    printf("%*spress :\n",width, "");
    while(menu -> string)
    {
        printf("%*d.) %s\n", width, pos++, menu -> string);
        menu++;
    }
}

const menu_type mm[] = 
{
    {"Display all existing products:", NULL},
    {"Add new product details:", NULL},
    {"Edit a existing product:", NULL},
    {"Make a purchase.", NULL},
    {"Delete a list :", NULL},
    {"Display Profit/loss is sales:", NULL},
    {"Display all product with zero quantity", NULL},
    {"Display all product with highest quantity", NULL},
    {"Change user password.", NULL},
    {"Exit the program.", NULL},
    {NULL, NULL},
};

int main(void)
{
    print_menu(40, mm);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68775440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档