更新终端上显示的文本 [英] Updating text displayed on the terminal
问题描述
我正在尝试用C语言创建生活游戏程序,但是我对更新终端上显示的输出的过程不是很熟悉.
I'm attempting to create a game of life program in C, but i'm not very familiar with a process to update the output displayed on the terminal.
因此,例如,我将拥有一个2d char数组,其中每个元素将包含一个#"或一个-".我将这个数组打印到屏幕上,但是我不想在每次状态改变时都打印一个新的2d数组,而是想用新状态覆盖终端中的旧数组.
So, for example, I will have a 2d char array, where each element will contain either a '#' or a '-'. I will print this array onto the screen, but rather than printing a new 2d array every time there is a state change, I want to overwrite the old array in the terminal with the new state.
我一直在寻找实现此目标的方法,但是运气还不太好.我发现最接近的是printf函数(\ r)中的回车符,但是希望有人可以告诉我执行此操作的最佳方法.
I have looked for ways to do this, but haven't had much luck. The closest I have found is a carriage return in the printf function (\r), but hopefully someone can tell me the best way to do this.
具体地说,我如何在屏幕上打印2d数组,更改数组的元素,并在旧数组的顶部打印出新数组,即覆盖它.
Specifically, how could I print out a 2d array on the screen, change the elements of the array, and print out the new array ON TOP of the old one, ie, overwrite it.
推荐答案
(其中一些链接,代码片段是Linux,其他是Windows)
给出您的具体问题 ,(并假设您确实知道如何向控制台写入数组):
(some of these links, code snippets are Linux, and others are Windows)
Given your specific questions, (and assuming you do know how to write an array to the console) :
1) 写入第一个数组.
2) ,然后清除控制台(或覆盖控制台)
像这样:
1) write the first array.
2) Then Clear The Console (or over write the console)
Something like this:
#include <stdlib.h>
void main()
{
system("cls");
}
或将以下内容写入stdout:(Linux)
Or write the following to stdout: (Linux)
write(1,"\E[H\E[2J",7);
/usr/bin/clear会执行此操作,除了不会创建另一个进程.
或全部:
which is what /usr/bin/clear does except it does not create another process.
Or both:
void clear_screen()
{
#ifdef WINDOWS
system ( "CLS" );
#else
// Assume POSIX
system ( "clear" );
#endif
}
3) 写下一个数组
3) write the next array
这篇关于更新终端上显示的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!