scanf error!!

Why the value of i an j are being printed ,even before the user is entering the char values?

#include<stdio.h>
#include<conio.h>
int ans;
int visited[101][101]={{0}};
char maze[101][101];
int dfs(int r,int c,int n,int m);
int main()
{
    int t,a,b,c,i,j,k,l,n,m;
    scanf("%d",&n);
    scanf("%d",&m);
    
    
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {scanf("%c",&maze[i][j]);printf("i   %d  j   %d\n",i,j);}
    }printf("cvbds %c\n",maze[1][1]);
      for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {printf("%c  %d   %d",maze[i][j],i,j);}printf("\n");
    }ans=0;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {printf("%c\n",maze[i][j]);dfs(i,j,n,m);}
    }
    
    printf("%d\n",ans);
    getch();
} 


int dfs(int r,int c,int n,int m)
{   if(visited[r][c]==1)
     return 0;
    visited[r][c]=1;printf("hiSDFAS   %d   %d    %c\n",r,c,maze[r][c]);
    if((maze[r][c]=='S')&&(r+1<=n)&&visited[r+1][c]==0)
    {printf("hi\n");dfs(r+1,c,n,m);}
    if((maze[r][c]=='N')&&(r-1>=1)&&visited[r-1][c]==0)
    {printf("viaksh\n");dfs(r-1,c,n,m);}
    if((maze[r][c]=='E')&&(c+1<=m)&&visited[r][c+1]==0)
    {printf("churu\n");dfs(r,c+1,n,m);}
    if((maze[r][c]=='W')&&(c-1>=1)&&visited[r][c-1]==0)
    {printf("maynk\n");dfs(r,c-1,n,m);}
    if((r==n)&&(c==m))
    {ans++;return 0;}    
        
}

It is happening because the keyboard buffer is non empty at starting. So maybe a trailing ‘\n’ is present in buffer and read by scanf, and program moves on.

To be certain, you should print out the value read from scanf.

And to remedy it, flush the buffers at start.

I suspect that you are using Turbo C++. Please, for your own good STOP using it.

As you are reading a character form this statement

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

when you press enter this statement takes it as a character and that’s why i and j value gets printed.

All you have to do is to use getchar() before the for loop. And always remember “pressing enter” or ‘\n’ both are taken as a character. So, be careful while reading string or characters.

1 Like

Change your scanf("%d", &m); to scanf("%d\n", &m);

That way, the newline will be taken care of, ‘automatically’.

Need formatting!!!

@sobhagya : If you have enough karma, you too can format.

1 Like

nope i m using DEV C++…??

nd how to flush??

oops my bad, you can’t flush it, you have to read it :stuck_out_tongue:

Use @sobhagya’s suggestion OR avoid scanf("%c"). I tend to do latter. scanf("%c") will bite you like it just did. Instead use scanf("%s"), as a string can be a single char too.

I would suggest against Dev too.

1 Like

thn what to use???