教えてください
Posted: 2010年12月29日(水) 14:04
C言語で、画面の中央に文字列を表示する場合は、どうしたらいいですか??
お願いします。
お願いします。
画面の中央ってど真ん中ということでよろしいですね?みやび さんが書きました:C言語で、画面の中央に文字列を表示する場合は、どうしたらいいですか??
お願いします。
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main()
{
HANDLE hStdout; // コンソール出力のハンドル
CONSOLE_SCREEN_BUFFER_INFO cinf; // コンソールスクリーン情報
COORD dwPos; // 位置情報
char *str = "HelloWorld"; // 出力文字列
int counter; // カウンタ
hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // コンソール出力のハンドル
GetConsoleScreenBufferInfo(hStdout, &cinf); // コンソールスクリーン情報を取得する
dwPos.X = (cinf.dwSize.X - strlen(str)) / 2; // 横の最大文字列から出力文字列を引いて二で割るとX軸は中央になる。
dwPos.Y = cinf.dwCursorPosition.Y + (cinf.srWindow.Bottom-cinf.srWindow.Top) / 2;
// ↑現在のカーソルの位置(Y軸) ↑ウィンドウの一番下の位置から一番上の位置を引けばウィンドウのY軸方向の幅が出る
// それを2で割ると中央の位置が出る。
if (!SetConsoleCursorPosition(hStdout, dwPos)) // カーソルの位置を設定する
{
return -1;
}
WriteConsole(hStdout, "HelloWorld", strlen("HelloWorld"), NULL, NULL); // 文字列を出力する。
for (counter = (cinf.srWindow.Bottom - cinf.srWindow.Top) / 2; counter > 0; counter--)
{// ↑あと半分を改行で埋める。
printf("\n");
}
getchar();
return 0;
}
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main()
{
HANDLE hStdout; // コンソール出力のハンドル
CONSOLE_SCREEN_BUFFER_INFO csbi; // コンソールスクリーン情報
int counter; // カウンタ
char *str = "HelloWorld"; // 出力文字列
hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // コンソール出力のハンドル
GetConsoleScreenBufferInfo(hStdout, &csbi); // コンソールスクリーン情報を取得する
for (counter = 0; counter < csbi.srWindow.Bottom - csbi.srWindow.Top; counter++) // 画面下まで改行
{
if (counter == (csbi.srWindow.Bottom - csbi.srWindow.Top) / 2) // ちょうど画面の半分に来たら
{
printf("%*s%s", (csbi.dwSize.X - strlen(str)) / 2, "", str); // X軸の半分になるように出力
}
printf("\n");
}
getchar();
return 0;
}