当我使用 Borland C++ 构建此代码时,为什么它不能正确定位光标?
我找到了仅使用 C 标准库的替换 gotoxy()
函数的代码。显然它使用 GCC 进行编译,其工作方式类似于 conio.h 中的 Gotoxy()。
不过,我只有 Borland C++ v5.5 编译器,它编译得很好,但不会像 conio.h
中的 gotoxy()
那样重新定位光标。任何人都可以验证这个在使用 GCC 时有效的事实,或者告诉我为什么它在使用 Borland 时不起作用吗?
#include<stdio.h>
#include<stdlib.h>
void gotoxy(int x, int y)
{
printf("%c[%d;%df", 0x1B, y, x);
}
int main()
{
gotoxy(10, 10);
printf("hello world");
}
I found this code for a replacement gotoxy()
function using C standard library only. apparently it compiles using GCC and works like the gotoxy()
found in conio.h
.
However I only have Borland C++ v5.5 compiler, this compiles fine but does not reposition the curser like gotoxy()
in conio.h
does. Can anybody verify the fact that this works when using GCC or tell me why it doesn't work using Borland?
#include<stdio.h>
#include<stdlib.h>
void gotoxy(int x, int y)
{
printf("%c[%d;%df", 0x1B, y, x);
}
int main()
{
gotoxy(10, 10);
printf("hello world");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数中使用的转义码取决于终端仿真器中的支持。它可能有效也可能无效,具体取决于您使用的环境。例如,您的程序在 Mac OS X 的终端应用程序中按预期工作,在 xterm 兼容模式下运行 bash。
您可以阅读 ANSI 转义码,了解有关此特定情况的更多信息,即“HVP – 水平和垂直位置”命令。
The escape codes being used in your function depend on support being present in your terminal emulator. It may or may not work, depending on the environment you're using. For example, your program works as expected in Mac OS X's Terminal application, running bash in xterm compatibility mode.
You can read about ANSI escape codes for more information about this specific case, which is the "HVP – Horizontal and Vertical Position" command.
该代码打印 ANSI 转义序列:[y;xf,因此仅适用于 ANSI 终端或支持 ANSI 代码的终端仿真器。
问题不在于 GCC 与 BC++,而是在支持 ANSI 的 unix 风格终端模拟器 中运行代码与 Windows CMD 窗口。
编辑:尝试将
gotoxy()
的主体更改为以下内容。示例中的转义代码将光标移动到上一行。以 H 结尾的代码应将光标定位到请求的 (Y,X) 坐标。EDIT2:由于提问者使用 Windows CMD 控制台,正确的解决方案是使用 SetConsoleCursorPosition()。 Win2k 及更高版本不支持或不完全支持 ANSI 转义。
That code prints an ANSI escape sequence:
<esc>[y;xf
, so will only work on an ANSI terminal, or a terminal emulator that supports ANSI codes.The issue isn't GCC vs BC++, but running in a unix-style terminal emulator that supports ANSI codes vs the Windows CMD window.
EDIT: try changing the body of
gotoxy()
to the following. The escape code in your sample moves the cursor to a previous line. The code ending in H should position the cursor to the requested (Y,X) coordinate.EDIT2: since the asker is using the Windows CMD console, the correct solution is to use SetConsoleCursorPosition(). ANSI escapes aren't supported, or are incompletely supported in Win2k and later.