#include
#include
void StringGrid(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",(width-strlen(s)-2)/2," ",s,(width-strlen(s)-2)/2," ");
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(){
StringGrid(20,6,"abcd1234");
return 0;
}
博客小白,希望大家能帮下下,我在学校参加比赛的题,谢谢各位了
以下是题目:
、格子中输出
StringInGrid函数会在一个指定大小的格子中打印指定的字符串。
要求字符串在水平、垂直两个方向上都居中。
如果字符串太长,就截断。
如果不能恰好居中,可以稍稍偏左或者偏上一点。
代码改好了,原来有bug,不好意思.
#include<stdio.h>
#include<string.h>
void StringGrid(int width, int height, const char* s) {
int i, j;
int count = 0;
int len = strlen(s)<width-2?strlen(s):width-2; //len用于确认最多能放进去的字符长度
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
if ((i == 0 && j == 0) || (i == 0 && j == width - 1) || (i == height - 1 && j == width - 1) || (i == height - 1 && j == 0)) //四个角打印+
printf("+");
else if (i == 0 || i == height - 1) //另外,上下边打印-
printf("-");
else if (j == 0 || j == width - 1) //另外,左右边打印|
printf("|");
//要保证中间行偏上,所以用(height-1)/2可以到达这样的效果,(width-len)/2,就是中间行字符串开始的位置
else if (i == ((height-1) / 2) && (j == (width - len) / 2 || (count&&count<len)))
printf("%c", s[count++]); //第一次输入后count为1,保证后面的能输出
else //其他地方打印空格
printf(" ");
}
printf("\n"); //换行
}
}
int main() {
StringGrid(10, 7, "abcd1234");
return 0;
}