Question

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.

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.

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.

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.

Était-ce utile?

La solution

(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) write the first array.
2) Then Clear The Console (or over write the console)
Something like this:

#include <stdlib.h>

void main()
{
   system("cls");
}     

Or write the following to stdout: (Linux)

write(1,"\E[H\E[2J",7);

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
 }  

More Options Here

3) write the next array

Autres conseils

You can try something like this:

#include<stdio.h>

int main(void)
{

printf ("#####-----\r");
printf ("-#####----\r");

}

Not sure if I really answered your question. And if this is not your answer then you are definitely looking for something like ncurses.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top