c. 打印输出居中对齐的解决方案



我试过使用%.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");
}

我想要这样的输出

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

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,"%sn",str);
}

不要忘记包含正确的标题。

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.) %sn", 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);
}

最新更新