0

タイトル通り。トリックを行う方法はありますか?画面の中央に「Hello World」を印刷したいとしましょう。

4

3 に答える 3

2

文字列を中央に配置するために必要なスペースの幅を知る必要があります。文字列の長さを知る必要があります。適切な数の空白、文字列、および改行を記述します。

#include <stdio.h>

int main(void)
{
    int width = 80;
    char str[] = "Hello world";
    int length = sizeof(str) - 1;  // Discount the terminal '\0'
    int pad = (length >= width) ? 0 : (width - length) / 2;

    printf("%*.*s%s\n", pad, pad, " ", str);
    return(0);
}

徹底的なテストプログラム(幅80まで):

#include <stdio.h>
#include <string.h>

int main(void)
{
    int width = 80;
    char str[81];
    for (int i = 1; i <= width; i++)
    {
        memset(str, 'a', i);
        str[i] = '\0';
        int length = i;
        int pad = (length >= width) ? 0 : (width - length) / 2;
        printf("%*.*s%s\n", pad, pad, " ", str);
    }
    return(0);
}
于 2013-03-09T17:03:50.920 に答える
1

SetConsoleCursorPosition関数を使用できます。コンソール ウィンドウの幅と高さを取得して呼び出します。

COORD coord;
coord.X = width / 2;
coord.Y = height / 2;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
于 2013-03-09T15:40:16.900 に答える
-1

C++ のように gotoxy() 関数を使用できますが、C では事前に定義されていないため、最初に定義する必要があります。もう 1 つの方法は、タブと改行 (\t と \n...) だけです。

于 2013-03-09T16:26:57.707 に答える