题目
格子中输出
StringInGrid函数会在一个指定大小的格子中打印指定的字符串。
要求字符串在水平、垂直两个方向上都居中。
如果字符串太长,就截断。
如果不能恰好居中,可以稍稍偏左或者偏上一点。
下面的程序实现这个逻辑,请填写划线部分缺少的代码。
#include <stdio.h>
#include <string.h>
void StringInGrid(int width, int height, const char* s)
{
int i,k;
char buf[1000];
strcpy(buf, s);
if(strlen(s)>width-2) buf[width-2]=0;
printf("+");
for(i=0;i<width-2;i++) printf("-");
printf("+\n");
for(k=1; k<(height-1)/2;k++){
printf("|");
for(i=0;i<width-2;i++) printf(" ");
printf("|\n");
}
printf("|");
printf("%*s%s%*s",_____________________________________________); //填空
printf("|\n");
for(k=(height-1)/2+1; k<height-1; k++){
printf("|");
for(i=0;i<width-2;i++) printf(" ");
printf("|\n");
}
printf("+");
for(i=0;i<width-2;i++) printf("-");
printf("+\n");
}
int main()
{
StringInGrid(20,6,"abcd1234");
return 0;
}
对于题目中数据,应该输出:
(如果出现对齐问题,参看【图1.jpg】)
注意:只填写缺少的内容,不要书写任何题面已有代码或说明性文字。
答案
(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2-1," ",buf,(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2+2," "
代码
1 #include <stdio.h> 2 #include <string.h> 3 4 void StringInGrid(int width, int height, const char* s) 5 { 6 int i,k; 7 char buf[1000]; 8 strcpy(buf, s); 9 if(strlen(s)>width-2) buf[width-2]=0; 10 11 printf("+"); 12 for(i=0;i<width-2;i++) printf("-"); 13 printf("+\n"); 14 15 for(k=1; k<(height-1)/2;k++){ 16 printf("|"); 17 for(i=0;i<width-2;i++) printf(" "); 18 printf("|\n"); 19 } 20 21 printf("|"); 22 23 printf("%*s%s%*s",(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2-1," ",buf,(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2+2," "); //填空 24 //(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2-1," ",buf,(width-2-strlen(buf))%2==0?(width-2-strlen(buf))/2:(width-2-strlen(buf))/2+2," " 25 printf("|\n"); 26 27 for(k=(height-1)/2+1; k<height-1; k++){ 28 printf("|"); 29 for(i=0;i<width-2;i++) printf(" "); 30 printf("|\n"); 31 } 32 33 printf("+"); 34 for(i=0;i<width-2;i++) printf("-"); 35 printf("+\n"); 36 } 37 38 int main() 39 { 40 StringInGrid(20,6,"abcd1234"); 41 StringInGrid(19,6,"abcd1234"); 42 StringInGrid(17,6,"abcd12345"); 43 return 0; 44 }
来源:https://www.cnblogs.com/memocean/p/12214914.html