Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

Draw ASCII frame with given dimensions (x, y) in C

i have a problem to draw a ASCII frame with user given dimensions (x, y). I have written some code that works for X coordinate, but don't know how to write loop for y dimension. I will be very grateful for any kind of help.

int main() {

    int dimension_1, dimension_2;

    printf("Give first size (x): ");
    scanf("%d", &dimension_1);
    printf("Give second size (y): ");
    scanf("%d", &dimension_2);

    // X
    printf("%c", 201);
    for (int i = 0; i < dimension_1; ++i)
        printf("%c", 205);
    printf("%c", 187);
    // Y !!! HERE DON'T KNOW WHAT TO DO ?
    printf("
%c", 186);
    printf("%c", 186);
    // X
    printf("
%c", 200);
    for (int i = 0; i < dimension_1; ++i)
        printf("%c", 205);
    printf("%c", 188);
}
question from:https://stackoverflow.com/questions/65928070/draw-ascii-frame-with-given-dimensions-x-y-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to draw the left side of the box, then add space characters to separate the left from the right side, then draw the right side of the box.

You can do this by writing an outer loop that spans the height of the box and an inner loop that spans the width of the box. The latter adds space characters.

#include <stdio.h>

int main() {
    int dimension_x, dimension_y;

    printf("Give first size (x): ");
    scanf("%d", &dimension_x);
    printf("Give second size (y): ");
    scanf("%d", &dimension_y);

    // Draw the top of the box.
    printf("%c", 201);
    for (int x = 0; x < dimension_x; x++)
    {
        printf("%c", 205);
    }
    printf("%c
", 187);
    
    // Draw the sides of the box.
    for (int y = 0; y < dimension_y; y++)
    {
        // Left side of box.
        printf("%c", 186);

        // Space separating the left and right sides.
        for (int x = 0; x < dimension_x; x++)
        {
            printf(" ");
        }

        // Right side of box.
        printf("%c
", 186);
    }
    
    // Draw the bottom of the box.
    printf("%c", 200);
    for (int x = 0; x < dimension_x; x++)
    {
        printf("%c", 205);
    }
    printf("%c", 188);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...