Creating a 50 x 50 grid

I had a question about C++ if anybody can answer it for me, I will really appreciate it.

Say I create an output file and I want to create a 50 x 50 grid in the file. How can I do this without using multidimensional arrays? I was thinking of this. However, I think the newline character on each line is not considered to be part of the canvas:

1
2
3
4
5
6
7
8
9
10
//set up 50x50 canvas
for(int i = 1; i <= 50; i++)
{
    outfile.put(' ');
    for(int j = 1; j <= 50; j++)

    outfile.put('\n');
}
//reset pointer to start of file
outfile.seekp(0, ios::beg);


One of the things I wish to accomplish with this grid is to be able to move the pointer around. Any help will be appreciated
Make sure you open the file in binary mode if you wish to seek and tell. Otherwise, I see no issue with what you have.

Perhaps if you could explain better what you are trying to accomplish...
I see no reason why you would want to avoid multidimensional arrays for this. Then you could store the grid very easily.
you can do this..

int grid[maxrow*maxcol];
grid[maxcol*desired_row+desired_col] = value; //same as a 2-d array grid[desired_row][desired_col].

there are 4 or 5 reasons why 1-d is the better way.
1) you can reshape something. Maybe you want to look at it as a 10x250 for some reason.
2) you can read and write it to a binary file without hassle
3) you can iterate, search / sort / more <algorithms> on the whole thing instead of per row which is faster for many needs
4) you can avoid some memory /paging problems easier
5) you can transpose /rotate/etc in place

all the above works for vector / valarray as well instead of vector<vector< design.


You have a problem with your nested loops.

Line 4: Each time though the outer loop you're writing a single space.

Lines 5-7: You output 50 NL characters.

If you want 50 lines of spaces, you want something like this:

1
2
3
4
5
for (int i = 1; i <= 50; i++)
{   for (int j = 1; j <= 50; j++)
        outfile.put (' ');
    outfile.put ('\n');
}


Topic archived. No new replies allowed.