Engineer999
Engineer999

Reputation: 3955

Writing to a file column by column C++

i'm struggling to find a way to this and can't seem to find any solution anywhere, but I imagine it has to be possible.

I would like to write to a file, column by column instead of row by row.I have an arrays of strings which get updated as my program is running. The strings look like this "--4---" , "1-----", "--15---", "----6-" etc.

These need to be written to a file aligned column by column, from left to right. eg. :

--1-------
----------
4----15---
----------
-------6--
----------

I am using ofstream. I could wait until a certain number of strings are updated, then print them row by row to the file, but it gets messy when I have numbers with two digits , as have to correct offsets in advance (each array index must be aligned) etc.

Thanks for any help

Upvotes: 1

Views: 1501

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57728

A better method is to model the file in memory, then write the memory to the file.

If your text representation has 5 columns, I recommend using a matrix with 6 columns and let the 6th column be a newline.

#define MAX_ROWS 4
#define MAX_COLUMNS (5+1)

char board[MAX_ROWS][MAX_COLUMNS];

// Initialize the board
for (size_t row = 0; row < MAX_ROWS; ++row)
{
  for (size_t column = 0; column < MAX_COLUMNS - 1; ++column)
  {
    board[row][column] = '-';
  }
  board[row][column] = '\n';
}
board[MAX_ROWS-1][MAX_COLUMNS-1] = '\0'; // Add terminating NULL.

You can then print the board by:

cout << (char *)(&board[0][0]) << endl;

Usually, writing to memory is a lot faster than writing to a file. Also, you can output the board in any format, such as CSV or XML.

Upvotes: 2

Related Questions