-1

I am getting weird results when I try to take input of a 2D char array for some reason. I have always taken integer 2D arrays in the past this way but somehow this method doesn't work for char arrays.

#include <stdio.h>

int main()
{
    int i,j,n;
    scanf("%d",&n);
    char a[n][n];
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            scanf("%c",&a[i][j]);
    }

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

Excepted Input:

3

a b c

d e f

g h i

Expected Output:

a b c

d e f

g h i

What happens:

3

a b c

d e f

(Input abruptly stops)

Output:

a b c

d

5
  • 3
    Can you please elaborate on the "doesn't work" part? How doesn't it work? What is your input? What is your expected output? What is the actual output? Please read about how to ask good questions. And also please learn how to debug your programs. Commented Nov 15, 2017 at 8:37
  • 1
    What do you input, what do you get, how does this differ from what you expected? Commented Nov 15, 2017 at 8:40
  • 1
    You probably want scanf("%c\n",&a[i][j]) (extra '\n' at the end) Commented Nov 15, 2017 at 8:42
  • 2
    @BarmakShemirani Better to add a space before the format. Otherwise the last scanf call will block until a non-space character is entered. Commented Nov 15, 2017 at 8:50
  • @Some programmer dude, right. I think it wouldn't need \n at all, just " %c" Commented Nov 15, 2017 at 9:11

1 Answer 1

3

Assuming you insert the input like this:

  1. a
  2. whitespace
  3. b
  4. whitespace
  5. c
  6. enter...

then your program has too many chars in the input buffer. You want to read 9 char with scanf("%c") and indeed 9 chars enter the buffer, but they include things you don't want (whitespaces and newlines).

Fix: add whitespace before %c like this - scanf(" %c",&a[i][j]);. This would ignore any sort of whitespace between chars read ('\n' '\t'" ' ').

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you so much :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.