I am trying to print a 2d matrix in c . I have a 2D array of integers. The output looks like this:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60
0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 100 100 100 100 100 100 100 100 100 100 160
My code simply does 2 loops and adds an space after each number (and a newline after every row). Is there an easy way to print nicely formatted matrix in cpp. Something that would be more readable like so:
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 60 60 60 60 60
0 0 0 0 0 0 60 60 100 100 160
Code:
for(int i = 0; i <= n ; i ){
for(int w = 0; w <= W ; w ){
std:cout<<some_array[i][w]<<" ";
}
std::cout << std::endl;
}
CodePudding user response:
This overload of the output stream operator will do the formatting for you. And then the code where you do the output will look quite clean.
#include <iostream>
template<typename type_t, std::size_t rows_v, std::size_t cols_v>
std::ostream& operator<<(std::ostream& os, type_t (&arr)[rows_v][cols_v])
{
// loop over the rows
for (const auto& row : arr)
{
// to print a comma between values
bool comma{ false };
// loop over the values in the row
for (const auto& value : row)
{
if (comma) os << ", ";
os << value;
comma = true;
}
os << "\n";
}
return os;
}
int main()
{
int arr[2][3]{{0,1,2},{4,5,6}};
std::cout << arr << "\n";
return 0;
}
CodePudding user response:
Quick code that does this, could be made better:
#include <iostream>
#include <string>
int main()
{
int maxwidth = 0;
int sz;
std::string s;
int K[3][31] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 160}};
for (int i = 0; i < 3; i )
{
for (int w = 0; w < 31; w )
{
s = std::to_string(K[i][w]);
sz = s.size();
maxwidth = std::max(maxwidth, sz);
}
}
maxwidth ; // we need to print 1 extra space than maxwidth
for (int i = 0; i < 3; i )
{
for (int w = 0; w < 31; w )
{
std::cout << K[i][w];
s = std::to_string(K[i][w]);
sz = (maxwidth - s.size());
while (sz--)
std::cout << " ";
}
std::cout << std::endl;
}
return 0;
}
Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60
0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 100 100 100 100 100 100 100 100 100 100 160