Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abnormal behavior of scanf [duplicate]

Tags:

c

scanf

I have code as below which scans a matrix, w - width of matrix, h - heigth of matrix.

I am using Visual Studio 2010.

Every time I get a char it increases j by 2 (I put the break point and come to know this behavior).

int w = 0, h = 0;
char map[21][21];
int i,j;

scanf("%d%d", &w, &h);
for(i = 1; i <= h; ++i){
    for(j = 1; j <= w; ++j){
        //fflush(stdin);
        scanf("%c",&map[i][j]);
        //fflush(stdin);
    }
}

What can be the reason behind this?

at the time of scan i am giving value, w = 7, h = 5.

I don't see any error in my code....Please help me.

like image 395
user2322888 Avatar asked Mar 23 '23 01:03

user2322888


1 Answers

The problem is due to '\n' characters (on pressing Enter ) left behind by scanf.
One way to eat up these newline character is place a ' ' before %c in scanf;

 scanf(" %c",&map[i][j]);  
        ^
        |
      space

Another way is to use a loop to eat up all the \n by getchar()

  int ch;
  while((ch=getchar())!='\n' && ch != EOF );
like image 184
haccks Avatar answered Apr 04 '23 21:04

haccks