how to print a matrix of 9x9

Hi , I have studied the arrays section here. Now I am trying to print a matrix that is retrieved from a file (map.txt) which has various numbers. It is a 9x9 grid with 81 numbers.

Can anyone please help me how to print it to the screen?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Example program
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
    std::ifstream f("map.txt");
    
    using Matrix = std::vector<std::vector<int>>;
    
    const size_t size = 9;
    
    Matrix matrix(size, std::vector<int>(size));
    
    for (size_t i = 0; i < size; i++)
    {
        for (size_t j = 0; j < size; j++)
        {
            f >> matrix[i][j];
            std::cout << matrix[i][j] << " ";
        }
        std::cout << "\n";
    }
}


(edit: fixed bugs)
Last edited on
Hello stephaniexx18,

Welcome to the forum.

You might give this a try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

constexpr std::size_t MAXSIZE{ 9 };

int main()
{
	int arr[MAXSIZE][MAXSIZE]{
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9},
	{1, 2, 3, 4, 5, 6, 7, 8, 9}
	};  // <--- Setup for testing.

	// After reading the file and filling the array.

	for (size_t row = 0; row < MAXSIZE; row++)
	{
		for (size_t col = 0; col < MAXSIZE; col++)
		{
			std::cout << arr[row][col] << (col + 1 < 9 ? ", " : "\n");
		}
	}

	std::cout << "\n\n\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}


Hope that helps,

Andy
Thank you Ganado for the example, vectors are newer to me as I have only started going into these so some comments with explanations would be fantastic.
A vector is basically a thin wrapper over an array. A vector of vectors is like an array of arrays, which is the same thing as a multi-dimension array. Andy's setup of arr works in almost the same way.

matrix[2] accesses the third row, matrix[2][3] accesses the int element at the 3rd row, 4th column.

std::vector<std::vector<int>> matrix(size, std::vector<int>(size)); declares a 2-dimensional vector (a vector of vectors), with 9 outer vector elements. Each outer vector element then contains an inner vector, also of size 9.

std::ifstream f("map.txt"); opens a file stream for the map.txt file.
f >> matrix[i][j]; puts the next number in the file into the [i][j]th element.

std::cout << matrix[i][j]; then prints that element to the screen.
Topic archived. No new replies allowed.