-2

I'm trying to write a simple console game.

I want to refresh console 30 times per second. Usually this is not a problem, but this time I'm working with an array of size 30x30, and printing it using two loops is simply not fast enough.

I noticed that

<code>printf( "%s\n", myarray );</code> 

is quick enough, but it doesn't work properly with 2d arrays.

Is there a function that will make my array appear "instantly" on screen?

I'm using this function to print my array:

void draw(char screen[32][31]){
    for (int x=0;x<32;x++){
        for (int y=0;y<31;y++){
            cout<<screen[x][y];
        }
        cout<<endl;
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • There is no quick way unfortunately. You have to write your own. – balki Dec 11 '18 at 17:08
  • 1
    Store your 2d array as a 1d array. Then you can print it with a single traversal. (you would have to embed newlines into it so it prints on multiple lines) – NathanOliver Dec 11 '18 at 17:08
  • 5
    30x30 is **tiny** and should be possible to print thousands of times per second. Maybe you're not building with optimisation enabled? Or you're doing something very inefficiently. We can't tell, because you haven't provided nearly enough information in your question. – Jonathan Wakely Dec 11 '18 at 17:09
  • 2
    2d array of *what*? `printf( "%s\n", myarray )` implies `char`, but I don't want to assume. If it isn't a `char` array, then what you have is undefined behaviour – Caleth Dec 11 '18 at 17:14
  • 5
  • 3
    since you are using , set sync_with_stdio() to false and check. Have a look at this https://stackoverflow.com/a/7579656/5281962 – Cherubim Dec 11 '18 at 17:21

1 Answers1

2

This should be faster:

void draw(char screen[32][31]){
    for (int x = 0; x < 32; x++){
        cout.write(screen[x], 31);
        cout << '\n';
    }
    cout << flush;
}

As noted in a comment above, endl is the wrong way to insert a newline, because it also flushes the stream and so removes the benefits of buffering done by the I/O library. See endl vs '\n' for more information.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521