我试过使用%.s,但是我不想在每一行都使用它,有什么解决方案吗?
#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这样的输出。
发布于 2021-08-13 17:42:04
我关注的是您在标题中提出的问题,而不是您的代码,因为您的代码做了一些非常不同的事情,并且与标题中的问题无关。
单独的printf()不能居中显示文本。您必须找出要打印的文本的长度,然后在需要对齐时打印填充空格字符。正如其他人所说,创建一个函数:
//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);
}别忘了包括正确的标题。
发布于 2021-08-13 17:16:28
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);
}https://stackoverflow.com/questions/68775440
复制相似问题