问题描述
我在互联网上搜索了这个,但由于某种原因它不起作用*这可能是因为那里的usleep和fflush。
介意向我解释他们做了什么 - 或者更好地给我一些我可以替换的东西?
I searched this in the internet and for some reason it doesn''t work *which is probably because of the "usleep" and "fflush" there.
mind explaining to me what they do--or better yet give me something that I can replace those with?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct { int *x, n; } tower;
tower *new_tower(int cap)
{
tower *t = calloc(1, sizeof(tower) + sizeof(int) * cap);
t->x = (int*)(t + 1);
return t;
}
tower *t[3];
int height;
void text(int y, int i, int d, const char *s)
{
printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d);
while (d--) printf("%s", s);
}
void add_disk(int i, int d)
{
t[i]->x[t[i]->n++] = d;
text(t[i]->n, i, d, "==");
usleep(100000);
fflush(stdout);
}
int remove_disk(int i)
{
int d = t[i]->x[--t[i]->n];
text(t[i]->n + 1, i, d, " ");
return d;
}
void move(int n, int from, int to, int via)
{
if (!n) return;
move(n - 1, from, via, to);
add_disk(to, remove_disk(from));
move(n - 1, via, to, from);
}
int main(int c, char *v[])
{
puts("\033[H\033[J");
if (c <= 1 || (height = atoi(v[1])) <= 0)
height = 8;
for (c = 0; c < 3; c++) t[c] = new_tower(height);
for (c = height; c; c--) add_disk(0, c);
move(height, 0, 2, 1);
text(1, 0, 1, "\n");
return 0;
}
推荐答案
ESC n ; m H
序列将光标定位到行n,列m。在过去的好时光中使用这些控制序列来控制基于字符的屏幕上的光标和其他属性。
如果输出设备不理解那些控制序列它只是打印带标签的字符。这可能是你没有看到任何东西的原因。 usleep和fflush对我来说很好看。根据您的平台查找了解ANSI控制序列的shell,您将没事。
sequence position the cursor to row n, column m. These control sequences were used in the good old days to control the cursor and other properties on a character-based screen.
If the output device doesn''t understand those control sequences it just prints garbeled characters. So that may be the reason you are not seeing anything. The usleep and fflush look ok to me. Depending on your platform look for shell that understands ANSI control sequences and you will be fine.
这篇关于河内的塔,跑步的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!