Home > OS >  How to print Char matrix?
How to print Char matrix?

Time:12-25

I'm very new to c , so excuse me for my stupid question. I can't print char matrix.

This is my code. I must not use strings!


#include <iostream>
using namespace std;

int main() {
    const int sizeX = 3;
    const int sizeY = 3;

    char matrix[sizeX 1][sizeY 1] = { {'a','b','c', '\0'},{'d','e','f', '\0'},{'g','h', 'k', '\0'}};

    for (int i = 0; i < sizeX; i  )
    {
        for (int j = 0; j < sizeY; j  )
        {
            printf("%d ", matrix[sizeX][sizeY]);
        }
        cout << endl;
    }
    
}


I found a lot of information about int matrix but nothing about char matrix, and i can't find my mistake.

CodePudding user response:

You are trying to print indexes sizeX and sizeY, when you actually want to print indexes i and j.

You are also using %d in printf, which is used for integers. %c is used for characters.

Also, there is no need to be mixing printf and std::cout here. These 2 examples do the same thing:

  • printf("%c ", matrix[i][j]);

  • std::cout << matrix[i][j] << " ";

CodePudding user response:

Here is what you wrote when you print,printf("%d ", matrix[sizeX][sizeY]);

You just always print matrix[sizeX][sizeY]. So what's the point of having all these cycles?

To fix this, you need to change it into printf("%d ", matrix[i][j]);

Also, if you want to print a char instead of the ASCII of the char. You need to change %d into %c.

In the end, I advise that do not use cout or cin while you are using printf() or scanf()

Best wishes to your coding road.

  • Related