0
#include <stdio.h>

int main(void)
{
  int i, b;
  char a[10][10];
  for (i = 0; i<10; i++)
  {
    for (b = 0; b<10; b++)
    {
      scanf("%c", &a[i][b]);
    }
  }

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

Im new to c and im struggling with creating a 2d array with size 10x10.

I really dont know why but when i input, for example, this:

--IHH---I-
-H--------
----------
----H-----
----IH----
----H-----
----H-----
-H--------
---------I
-HI--H---I

I should be getting exactly the same, meaning:

--IHH---I-
-H--------
----------
----H-----
----IH----
----H-----
----H-----
-H--------
---------I
-HI--H---I

but it gives me this:

--IHH---I-
-H--------
----------
----H-----
----IH----
----H-----
----H-----
-H--------
---------I
-

But i discovered that instead of the code above i try this one:

#include <stdio.h>

int main(void)
{
  int i, b;
  char a[10][10];
  for (i = 0; i<10; i++)
  {
    for (b = 0; b<11; b++)
    {
      scanf("%c", &a[i][b]);
    }
  }

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

Magically i get this output:

--IHH---I--
-H---------
-----------
----H------
----IH-----
----H------
----H------
-H---------
---------I-
-HI--H---I

As you can see I did not entered more "-" but every line except the final has another "-" at the end. I am confused.

Rootsyl
  • 65
  • 5

2 Answers2

1

You should use scanf like this

scanf(" %c", &a[i][b]);

It will solve your problem, it is occurs because scanf adds newline char (\n) in your array. With this you can skip newline char.

Also you can check this for clear undestanding. scanf() leaves the new line char in the buffer

Muhammedogz
  • 774
  • 8
  • 21
1

I've found scanf way too difficult to use well. It is stateful, and a little magical, and not adding any value for you to understand what is going on.

Your input has control characters in it. Every line ends in a newline, or maybe a return and linefeed. Use getc to get and print one character at a time, and you'll see what you are really dealing with.

There are 11 (or 12) characters coming in per line, but you have allocated space for only 10. You could discard the extra control characters.

The reason you are seeing '-` at the "end" of the first nine lines is because you are actually showing the first character of the next row in you array.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119