Why doesn't my for loop accept 9 inputs?

My code takes only 5 values. What am I doing wrong?

#include<stdio.h> #include<stdlib.h> int main() { char arr[3][3]; int i,j,n; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%c",&arr[i][j]); } } return 0; } 

How can I fix it?

+4
source share
5 answers

Change

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

to

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

Note the space before the specifier to consume \n on the left in the stdin buffer when you press enter.

Each \n works as an input, occupying your space from the input space.

+8
source

It should work, but note that %c will only read one character. Spaces are not suppressed, as for other (more "higher-level") format specifiers, so if you separate your characters with spaces of any type, they will be read instead of the actual characters.

Also note that you should check the return value of scanf() , it may fail if there is no suitable input.

+3
source

The first input is stored in arr [0] [0], and then when you press enter (return key), it is stored in arr [0] [1], and when you think that you enter the second character, you are actually give the third entrance. Try the code below to see if you received it.

 #include<stdio.h> #include<stdlib.h> int main() { char arr[3][3]; int i,j,n; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Input array [%d][%d]",i,j); scanf("%c",&arr[i][j]); } } } 

As for the correction, you need scanf(" %c",&arr[i][j]); space infront% c to use \n

I hope he answers your question.

+1
source

You can use gets(arr[i][j]) instead

instead of scanf("%c",&arr[i][j]);

This will work just fine. It is recommended to use the gets() and puts() function instead of the printf() and scanf() functions for the string and character in C

0
source

you can use fflush (stdin)

 char arr[3][3]; int i,j,n; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%c",&arr[i][j]); fflush(stdin); } } 
-2
source

Source: https://habr.com/ru/post/1499319/


All Articles