By user2322888

2013-10-12 17:51:37 8 Comments

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){

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.


@Captain'Flam 2017-09-27 17:49:06

Here is an answer to vuppala srikar. His question "fscanf issue while reading input from text file [duplicate]" does not appear to me to be an exact duplicate :

In his question, the scanf is done on an opened text file (fptr).

Instead of :

while((fscanf(fptr,"%c %d",&c,&val))==2)
    printf("%c %d\n",c,val);

which reads only the first line of the file, I suggest :

char line [50] ;
while (fgets( line,sizeof( line ),fptr ))
    if (sscanf(line,"%c %d",&c,&val)==2)
        printf("%c %d\n",c,val);

I hope my answer arrives not too late...

@haccks 2013-10-12 19:10:11

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]);  

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

  int ch;
  while((ch=getchar())!='\n' && ch != EOF );

@Jonathan Leffler 2013-10-12 19:22:58

It will work if the user presses enter several times; the blank in the format eats up all the spaces, tabs, newlines before the next non-blank character is read by %c.

@haccks 2013-10-12 19:27:26

@JonathanLeffler; Yes you are right. I thought about reading by getchar. That's why I mistaken. Edited now.

@P0W 2013-10-12 17:53:33

You need to skip trailing newline from previous scanf

Don't use fflush(stdin)


int c;

while((c=getchar())!='\n' && c != EOF ); //eats newline came from scanf

after scanf call

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] visual studio wont scanf

8 Answered Questions

19 Answered Questions

2 Answered Questions

[SOLVED] Reading a string with scanf

  • 2011-03-23 14:40:55
  • abeln
  • 546080 View
  • 147 Score
  • 2 Answer
  • Tags:   c scanf

4 Answered Questions

1 Answered Questions

[SOLVED] Reading Input - gets scanf - Newbie

Sponsored Content