abnormal behavior of scanf [duplicate]

2019-01-02 21:42发布

This question already has an answer here:

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.

标签: c scanf
3条回答
浮光初槿花落
2楼-- · 2019-01-02 22:08

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 );
查看更多
只若初见
3楼-- · 2019-01-02 22:12

You need to skip trailing newline from previous scanf

Don't use fflush(stdin)

Use:

int c;

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

after scanf call

查看更多
不再属于我。
4楼-- · 2019-01-02 22:14

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...

查看更多
登录 后发表回答