Kudayar Pirimbaev
Kudayar Pirimbaev

Reputation: 1320

C: Logical error in scanning input

I have the following implementation of reading character matrix and printing it back. It works fine, but when I give matrix for it, it waits for another character and then outputs matrix properly. How can I fix it so that I would not need to input another character?

Sample input

3 4
0001
0110
1110

Sample output

0001
0110
1110

My code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, m; /* n, m - dimensions of matrix */
    int i, j; /* i, j - iterators */
    char **matrix; /* matrix - matrix input */
    scanf ("%d %d\n", &n, &m);
    matrix = (char **) malloc (sizeof (char *) * n);
    for (i = 0; i < n; ++i)
    {
        matrix[i] = (char *) malloc (sizeof (char) * m);
    }
    for (i = 0; i < n; ++i)
    {
        for (j = 0; j < m; ++j)
        {
            scanf ("%c ", &matrix[i][j]);
        }
    }
    for (i = 0; i < n; ++i)
    {
        for (j = 0; j < m; ++j)
        {
            printf ("%c", matrix[i][j]);
        }
        printf ("\n");
    }
}

Thanks in advance.

Upvotes: 0

Views: 62

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40145

        scanf ("%c", &bitmap[i][j]);
    }
    getchar();

Upvotes: 0

P.P
P.P

Reputation: 121407

Put the space before %c. If you have the whitespace after %c, scanf() would keep reading and ignoring all whitespaces. Hence you are forced to input a non-whitespace character.

Change:

    scanf ("%c ", &bitmap[i][j]);

to:

        scanf (" %c", &bitmap[i][j]);

Upvotes: 1

sha1
sha1

Reputation: 143

Before printing the characters, using fflush(stdout); might help. printf() and scanf() may sometimes be problematic when they are used together.

Upvotes: 0

faroze ibnejava
faroze ibnejava

Reputation: 11

try omitting space in the scanf("%c "). terminal may be expecting a space for input

Upvotes: 1

Related Questions