Array with characters in c

I'm all new to C and just wanted to try some programs for fun! My first idea was to create a Tic-Tac-Toe game. In the following code, I am trying to create a field. It works to a certain extent, but when I tested, recording feld[1][0]

and feld[2][0]

empty. Also what I don't understand is if I save more than one letter in the entry, like xx, it appears somewhere else. I guess this is an issue with keeping space assignment C. Glad for any feedback!

#include <stdio.h>
main()
{
  int i,j;
  char feld[3][3];
  for(j=0; j<3; j++)
  {
    for(i=0; i<3; i++)
    {
      printf("\t %2i. column %2i. row: ", i+1, j+1);
      scanf("%s", &feld[i][j]);
    }
  }
  for(j=0; j<3; j++)
  {
    for(i=0; i<3; i++)
    {
      printf("\t %c", feld[i][j]);
    }
    printf("\n");
  }
}

      

+3


source to share


3 answers


With this line:

scanf("%s", &feld[i][j]);

      

you read a string (multiple characters) and place them where there should only be one character. This will damage the symbols that are stored nearby. Use something like:

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

      



read only one character each time. But this solution is also not ideal, because now if you feed too many characters, they will remain saved until you try to read them again, which will lead to some odd behavior, such as printing multiple times without waiting for your inputs:

2. column 1. row:     3. column 1. row:     1. column 2. row:  

      

The correct answer depends on what you want if you feed multiple inputs at the same time.

+2


source


Below is the working code. Each element of the array is a symbol. %s

used to scan a string, not a character. You need to use %c

. Add a space before %c

scanf to eat / swallow spaces and special characters. (For example, enter)



#include <stdio.h>
main()
{
int i,j;
char feld[3][3];
for(j=0; j<3; j++)
{
    for(i=0; i<3; i++)
    {
        printf("\t %2i. Row %2i. Column:\n ", j+1, i+1);
        scanf(" %c", &feld[j][i]);
}
}
for(j=0; j<3; j++)
{
    for(i=0; i<3; i++)
    {
        printf("\t%c", feld[j][i]);
    }
    printf("\n");
}
}

      

+1


source


First of all, in your code, 'j' represents a string, so it must be the first and I must be after feld [j] [i] AND the second char size is 1, so we can only store one char, so the problem is using more than one entrance.

#include <stdio.h>
main()
{
int i,j;
char feld[3][3];
for(j=0; j<3; j++)
{
for(i=0; i<3; i++)
{
    printf("\t %2i. column %2i. row: ", i+1, j+1);
    scanf("%c", &feld[j][i]);
}
}
for(j=0; j<3; j++)
{
for(i=0; i<3; i++)
{
    printf("\t %c", feld[i][j]);
}
printf("\n");

      

}}

0


source







All Articles