1

I'm a beginner in C and am currently experiencing some troubles invovling chars. I'm having an issue trying to enter values in a char matrix and then print it.

Here's my code:

#include <stdio.h>
#define N 3

int main( )
{

char arr[N][N]={{0}};
int i,j;

for(i=0;i<N;i++){
    for(j=0;j<N;j++){
        scanf("%c",&arr[i][j]);
    }
}

for(i=0;i<N;i++){
    for(j=0;j<N;j++){
        printf("%c",arr[i][j]);
    }
}

return 0;
}

There are two chars that are missing at the end of the output.

I don't know what I'm doing wrong and I would like to understand my mistake:

-Is it some kind of problem involving the scanf fonction? I've heard about the buffer before, is that related? Is the problem coming from the moment I press enter?

-Am I initializing my matrix in a wrong way?

-Is it better to use getchar() in this situation? If so, how can I manage to enter exactly N*N values and not more?

Thanks a lot. Jordan.

Jewgah
  • 51
  • 8
  • "There are two chars that are missing at the end of the output." --> posting the input, the output and the expected output are useful parts of post like these. – chux - Reinstate Monica Jun 13 '16 at 17:24

3 Answers3

6

You should use " %c" to accept char as input. When you add a space before "%c" it consumes white-spaces (newline, tab, space, etc.) entered with previous inputs.

#include <stdio.h>
#define N 3

int main() {

    char arr[N][N]={{0}};
    int i,j;

    for(i=0;i<N;i++){
        for(j=0;j<N;j++){
            scanf(" %c",&arr[i][j]);
            //     ^ --- the space before %c
        }
    }

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

    return 0;
}

Input:

a b c d e f g h i

You can also input these characters one by one using Enter or Return button.

Output:

a b c 
d e f 
g h i 

You may also check this post which addresses the same issue.

Community
  • 1
  • 1
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
1

Another way to do this.. Add getchar(); statement after scanf() statement.

for(i=0;i<N;i++){
    for(j=0;j<N;j++){
        scanf("%c",&arr[i][j]);
        getchar();
    }
}

getchar() will consume tailling new lines.

NayabSD
  • 1,112
  • 2
  • 15
  • 26
1

In this case, just enter the 9 characters in sequence without pressing enter button like

123456789\n  

because putting a newline character after each character is stored in one of character index becuase \n is a character itself which surely you don't want to be entered like this

1\n2\n3\n4\n5\

In above case only 5 characters would be taken from user intentionally.

Mazhar
  • 575
  • 5
  • 20