scanf函数的异常行为 [英] abnormal behavior of 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屋!