字符数组在C消隐 [英] character array blanking in c
问题描述
code
int main()
{
int n,m,i,j;char a[10][10];
printf("enter n and m values\n");
scanf("%d%d",&n,&m);
printf("enter array values");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%c",&a[i][j]);
printf("the array is \n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
printf("%d %d %c\t",i,j,a[i][j]);
}
输入
Enter n and m values
4 5
Enter characters
11111000001111100000
输出
0 0
0 1 1 0 2 1 0 3 1 0 4 1 1 0 1 1 1 0 1 2 0 1 3 0 1 4 0 2 0 0
2 1 1 2 2 1 2 3 1 2 4 1 3 0 1 3 1 0 3 2 0 3 3 0 3 4 0
错误
如果我给的4 n值和M 5,scanf函数做它的工作。
If I give the value of n as 4 and m as 5 ,scanf does it job.
不过,虽然打印时i的值是0,j为0它不打印任何东西。
But while printing when the value of i is 0 and j is 0 it does not print anything.
同时一个[0] [1]将打印第一输入和一个[0] [2]将打印第二输入和连续,所以最后的输入0丢失时打印
Meanwhile a[0][1] prints the first input and a[0][2] prints second input and consecutively , so last input 0 is missing while printing.
请解释为什么[0]避免[0]。
Please explain why a[0][0] is avoided.
推荐答案
previous scanf函数
通话留下 \\ n
字符输入缓冲区,与输入一起去上pressing <大骨节病>输入骨节病>或<大骨节病>返回骨节病>键。 scanf函数(%C,和放大器;一个[I] [J]);
读取 \\ n
第一次迭代。
Previous scanf
calls leave behind \n
character in the input buffer which goes along with input on pressing Enter or Return key. scanf("%c",&a[i][j]);
reads that \n
on first iteration.
您需要刷新您的输入缓冲区。无论是在 scanf函数
You need to flush your input buffer. Either place a space before %c
in scanf
scanf(" %c", &a[i][j]);
^A space before `%c` can skip any number of leading white-spaces
也可以使用
int c;
while((c = getchar()) != '\n' && c != EOF);
NOTE: Will fflush(stdin)
work in this case?
fflush
是输出流只定义了。由于其冲的定义是完成缓冲字符的写入(不是丢弃它们),丢弃未读的投入会不会是 fflush
输入流类似的含义。
fflush
is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning forfflush
on input streams.
推荐阅读: C-FAQ 12.18
这篇关于字符数组在C消隐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!