scanf函数的异常行为 [英] abnormal behavior of scanf

查看:252
本文介绍了scanf函数的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code作为低于该扫描矩阵,W - 矩阵的宽度h - 矩阵heigth

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

我使用Visual Studio 2010。

I am using Visual Studio 2010.

每次我得到它2增加J A CHAR(我把破发点,来到知道这个行为)。

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?

在扫描我给值,W =时7,H = 5。

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

我看不出有任何错误在我的code ....请帮帮我。

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

推荐答案

该问题是由于的'\\ n'字符(在pressing <大骨节病>输入)通过 scanf函数甩在身后。结果
吃了这些换行符的一种方法是将%C scanf函数;

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

另一种方法是使用一个循环吃了所有的 \\ n 的getchar()

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

这篇关于scanf函数的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆