Search code examples
c++ncurses

ncurses printw bug when embedded in double for loop, c++


I am making a simple game in c++ that outputs to the console. Im using printw for this with ncurses. To print the grid, I have a for loop as follows:

for (int j; j < height + 2; j ++){
    for (int i; i<width+2; i++){
        printw("#");
    }
    printw("\n");
}

The output of this is just one line of #'s. At first I thought maybe it had something to do with the variable height, so I replaced it with its value, 22. Same, failed result. Then I physically typed out two for loops like this:

for (int i; i<width+2; i++){
    printw("#");
}
printw("\n");
for (int i; i<width+2; i++){
    printw("#");
}

and I got two lines of #'s! Really weird bug. I also tried while loops, but I had the same failed result. I'm new to c++, I come from python, so I could be missing something super obvious here. Thanks in advance!


Solution

  • You're not initialising your variables to 0, so they could be anything! Rewrite it like this:

    for (int j = 0; j < height + 2; j ++){
        for (int i = 0; i<width+2; i++){
            printw("#");
        }
        printw("\n");
    }