0

I have the following member function:

void Matrix::print(std::ostream &os) {
    for (unsigned i = 0; i < m_height; ++i) {
        os << "| ";
        for (unsigned j = 0; j < m_width; ++j) {
            os << this->matrix[i][j] << " ";
        }
        os << "|" << "\n";
    }
    os << "\n";
}

which takes in an ostream as an input and prints out a matrix of doubles in a two dimensional array format. The bars I have added at the end of each row works great to simulate the appearance of a two dimensional array if all of the entries have the same number of digits, e.g., all entries are integers between 10 and 99 inclusive. However, the output is misaligned if the entries each have a different number of digits.

I was wondering if there was a quick fix for this, possibly to control the precision of each entry to a fixed length so that the output is aligned properly, or some other option.

C Squared
  • 101
  • 4
  • does this answer you question? [Formatting output in C++](https://stackoverflow.com/questions/11226143/formatting-output-in-c) – ozerodb May 30 '21 at 09:08
  • @ozerodb no not really... I'll try and work with it though – C Squared May 30 '21 at 09:36
  • what isn't working? the only problem I might think of is that: by not knowing the items, you don't know the max lenght of an item before printing, is this it? If so, you can iterate over the matrix, take note of the longest item (i.e most digits) and then use std::setw with the noted max lenght as the parameter – ozerodb May 30 '21 at 10:17
  • @ozerodb this was similar to one of my previous thoughts but i didn’t know how to get the length of a double for some given decimal precision. – C Squared May 30 '21 at 10:19
  • mhhh.. you can convert the double to string maybe? and simply take the length of the string? Though this might slow down the program a lil bit.. – ozerodb May 30 '21 at 10:26
  • @ozerodb i’ll try to implement that, thanks. not too worried about how fast this function runs. just making a program that performs matrix operations and i want the output to be fairly readable. – C Squared May 30 '21 at 10:29
  • 1
    alrighty, let me know if it works as expected c; – ozerodb May 30 '21 at 10:30
  • Pleas show the expected and actual output in your question. And preferably a [mcve] (with emphasis on the minimal part) as well. – Some programmer dude May 30 '21 at 11:30

0 Answers0