I need to print centered string inside a frame of square stars pattern.
EXAMPLE:
const char tekst[]="This is example of string programming in C"; int width = 20; OUTPUT:
********************
* This is example *
* of string progr- *
* amming in C *
********************
If number of spaces that need to be added is odd, excess space should be added to the right. If the whole word cannot fit in the row, dash is added and word continues in the next row. Auxiliary strings are not allowed. Code:
#include <stdio.h>
#include <string.h>
void framed(const char *tekst, int width) {
int i, j = 0, count = 0;
for (i = 0; i < width; i )
printf("*");
printf("\n");
while (tekst[j] != '\0') {
count ;
if (count == 1)
printf("* ");
printf("%c", tekst[j]);
j ;
if (count 5 > width) {
printf(" *");
printf("\n");
count = 0;
}
if (j == strlen(tekst))
for (i = 0; i < width - count; i )
printf(" ");
}
printf("*\n");
for (i = 0; i < width; i )
printf("*");
}
int main() {
const char tekst[] = "This is example of string programming in C";
int width = 20;
framed(tekst, width);
return 0;
}
This is my output:
********************
* This is example *
* of string progra *
* mming in C *
********************
Could you help me to fix my code for correct output?
CodePudding user response:
Here you take the additional character "* "" *"
into account (with a little off-by-one because of >
):
if (count 5 > width)
Here you don't:
for (i = 0; i < width - count; i )
If you do take them into account, it (the frame) works.
for (i = 0; i <= width - (count 5); i )
assuming that you also output consistently a little later
printf(" *\n");
I recommend to replace the very magic number 5 with the less magic number of additional characters; 4 for "* *"
and to adapt the conditions <=
and >
.
The other differences to required output (centering instead of left aligning and inserting the "-" correctly have not even been attempted by the shown code, so I assume that they are not part of what is asked about.