gpt4 book ai didi

c - 用C语言编写的Windows

转载 作者:行者123 更新时间:2023-11-30 21:16:13 26 4
gpt4 key购买 nike

用 C 语言制作由文本组成的简单窗口或框的最快、最简单的方法是什么?即使是一个里面有文字的正方形也很好。我不想使用任何外部库,只是使用文本。

编辑:我使用的是 Windows。我看到你提到了 windows.h 库,但我不必使用它。我的意思是,这个问题很简单。我只是想要一种简单快速的方法将文本放入框中,即使使用简单的 printfs。

例如:

printf("+-------------+\n");
printf("| HELLO WORLD |\n);
printf("+-------------+\n");

最佳答案

如果您想要一个由星星制成的盒子,请执行以下操作:

#include <stdio.h>

int main()
{
int r, c, row, col;

printf("Enter number of rows: ");
scanf("%d", &row);
printf("Enter number of columns: ");
scanf("%d", &col);
printf("\n\n");

for(r = 0; r < row; r++)
{
for(c = 0; c < col; c++)
{
if(r > 0 && r < row - 1)
{
if(c > 0 && c < col - 1)
{
printf(" ");
}
else
{
printf("*");
}
}
else
{
printf("*");
}
}
printf("\n");
}

return 0;
}

它有效,取自 here ,但稍作修改。

此外,您还提到您想在其中写入文本。因此,请使用 gotoxy 函数。我已经提供了 Linux 和 Windows 的代码,因为您没有提到您正在使用的具体操作系统。

对于 Windows,取自 here :

#include <stdio.h>
#include <windows.h>

void gotoxy (int x, int y)
{
COORD coord; // coordinates
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

适用于 Windows(未测试)和 Linux,取自 here :

#include <stdio.h>

void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}

您在其中传递 xy 坐标,它会设置光标位置。然后,您使用 printf 打印的任何内容都将在该位置打印。

gotoxy 的第二个实现是如何工作的?

这与 here 上提出的问题完全相同。 :

This is using terminal escape codes to position the cursor.

"\x1B" is the escape character that tells your terminal that what comes next is not meant to be printed on the screen, but rather a command to the terminal (or most likely terminal emulator)

The trailing 'f' indicates that you want to force the cursor position somewhere, indicated by the coordinates that precede it.

Force Cursor Position <ESC>[{ROW};{COLUMN}f

So if you call gotoxy(4,2), it ends up sending the escape sequence "(ESC)[2;4f" where ESC is the byte 0x1B.

注意:如果您不想使用windows.h,并且仅使用printf,请使用第二个版本。我相信它也可以在 Windows 中工作,并且不需要 windows.h。不过,我无法测试它,因为我在 Ubuntu 中工作,而不是在 Windows 中。如果它不适用于 Windows,请通知我,我将编辑我的答案。

关于c - 用C语言编写的Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35576403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com