简体   繁体   中英

Unable to print multi-line strings in C

I am trying to print a series of multi-line strings (ascii art letters here), and when printing them out, the top of each letter moves to the right while the rest of the letter stays in the same position. Here is a screenshot of what occurs: 错误图像

I do not know why this is happening, as I am fairly new to C; if you have any knowledge about this, please share it!


#include <stdio.h>
#include <curses.h>

typedef const char letter[];


letter Y = 
"___      __\n
\\ \\__ / /\n
 \\ \\ / /\n
 |  |  |\n
 |  |  |\n
 |__|__|\n";

letter O =  
"_______ \n
/   __ \\\n
|  |  | |\n
|  |__| |\n
\\_______/\n";

letter U = 
" __    __ \n
 / |   | \\\n
|  |   |  |\n
|   \\_/   |\n
\\_________/\n";

letter L = 
" _\n"
"| |\n"  
"| |\n"
"| |__\n"
"|____/\n";

letter S =
" _________\n"
"/   _____/\n"
"\\_____  \\\n"
"/        \\\n"
"/_______  /\n"
"        \\/\n";

letter T =
"___________\n"
"\\__    ___/\n"
"   |   |\n"
"   |   |\n"
"   |___|\n";

letter EXCLAMATION_POINT =
"_________\n"
"\\\\\\\\|////\n"
" \\\\\\|///\n"
"  \\\\|//\n"
"   \\|/\n"
"   ***\n"
"   ***\n"
"    *\n";

const char *MESSAGE[] = {Y, O, U, L, O, S, T, EXCLAMATION_POINT};

int main() {
    initscr();
    cbreak();
    noecho();

    int maxY, maxX;
    getmaxyx(stdscr, maxY, maxX);

    int spacingPerLetter = maxX / 8;
    
    for (int i = 0; i < 8; i++) {
        mvprintw(maxY / 2, spacingPerLetter * (i + 1), MESSAGE[i]);
        refresh();
        getch();
        clear();
    }

    endwin();
    return 0;
}

The main problem is the newline embedded inside the strings you print.

The first "line" of the letters will be printed in the correct position, but then the newline will reset the position to the first column on the next line.

I recommend that you print each "letter" line by line (without the newlines). This could be helped by having each "letter" be an array of arrays of characters, where each sub-array is one line of the letter:

#define LETTER_WIDTH   11
#define LETTER_HEIGHT   6

const char Y[LETTER_HEIGHT][LETTER_WIDTH] = {
    "___      __",
    "\\ \\__ / /",
    " \\ \\ / / ",
    " |  |  |   ",
    " |  |  |   ",
    " |__|__|   "
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM