Ruhe
Ruhe

Reputation: 79

How to fill a two dimensional array with chars in C?

The point of the code is to create a 2D array of dimensions set by the user. After being prompted for the width and height, the user must put in char values into each position in the 2D array. When implemented with int: (int mat, int value), the algorithm works fine, however when trying to implement with char(char mat, char value), the output is not consistent with the integer version. The only changes are the type of array and value, as well as setting the scanf/printf("%d") to scanf/printf("%c). Any way you can implement this 2D array with chars?

#include <stdio.h>

int main() {

    int width;
    int height;

    printf("Enter col and row values between 2 and 20.\n");
    scanf("%d %d", &width, &height);
    printf("The numbers you typed was %d %d\n", width, height);

    char mat[height][width];
    int i;
    int j;
    char value;

    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            printf("Enter your value.\n");
            scanf("%c", &value);
            mat[i][j] = value;
        }
    }

    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            printf("%c", mat[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Upvotes: 2

Views: 3747

Answers (2)

David Schwartz
David Schwartz

Reputation: 182753

... the output is not consistent with the integer version

Well, of course not. It will be characters rather than integers. Otherwise, it will be the same.

Also, your input loop is really weird.

for (i = 0; i < height; i++) {
    for (j = 0; j < width; j++) {
        printf("Enter your value.\n");
        scanf("%c", &value);
        mat[i][j] = value;
    }
}

It seems like you're trying to prompt for each character, but then you only read a single character. I can't imagine how you expect anyone to use that. If I want to put in an "A", I type "A", but then nothing will happen until I press enter. But that will input two characters. So this code seems somewhat poorly designed.

As a quick fix, you could try something like:

for (i = 0; i < height; i++) {
    for (j = 0; j < width; j++) {
        printf("Enter your value.\n");
        do scanf("%c", &value);
            while (value == '\n' || value == '\r');
        mat[i][j] = value;
    }
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

Change this statement the following way

scanf(" %c", &value);
      ^^^^

Also change this statement something like

printf("Enter your character value: ");

that it would be more clear what the program expects to be entered.

Upvotes: 0

Related Questions