Search code examples
carraysmultidimensional-arrayconways-game-of-life

Printing a 2D Character Array - Last input cut off


I'm making the game of life in which the user specifies the dimensions of the grid, and then inputs the data to fill the grid.

X= Live

. = Dead

The problem with my current code is if the user say wants a 3x3 grid (9 values), when printing the grid, 8 are output. I've tried changing the conditions to <=, or starting the loops with -1 but this doesn't seem to work

I've used loops i've seen on other posts such as: Printing a 2D array in C but the problem still persists.

Heres the code:

int WIDTH, HEIGHT, CYCLES;
scanf("%d %d %d",&WIDTH,&HEIGHT,&CYCLES);

//Grids
char grid[HEIGHT][WIDTH];
char temp[HEIGHT][WIDTH];

//Columns + Rows
for (int row = 0; row <HEIGHT ; ++row)
{
    for (int col = 0; col <WIDTH ; ++col)
    {
        scanf("%c",&grid[row][col]);
    }
}

for (int row = 0; row <HEIGHT ; ++row)
{
    for (int col = 0; col <WIDTH ; ++col)
    {
        printf("%c",grid[row][col]);
    }
}

Appareciate any help


Solution

  • Changing

    scanf("%c",&grid[row][col]);
    

    to

    scanf(" %c",&grid[row][col]);
    

    Adding a Space before %c fixed this. Cheers to @WhozCraig