-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

Stargateur
  • 24,473
  • 8
  • 65
  • 91
mr_mohapatra
  • 17
  • 1
  • 9
  • 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](http://stackoverflow.com/help/how-to-ask). And also please [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Some programmer dude Nov 15 '17 at 08:37
  • 1
    What do you input, what do you get, how does this differ from what you expected? – alk Nov 15 '17 at 08:40
  • 1
    You probably want `scanf("%c\n",&a[i][j])` (extra `'\n'` at the end) – Barmak Shemirani Nov 15 '17 at 08: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. – Some programmer dude Nov 15 '17 at 08:50
  • @Some programmer dude, right. I think it wouldn't need `\n` at all, just `" %c"` – Barmak Shemirani Nov 15 '17 at 09:11

1 Answers1

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'" ' ').

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124