C中的字符数组消隐

2023-12-26

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

Input

 Enter n and m values  
 4 5
 Enter characters 
 11111000001111100000

Output

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   

Error

如果我将 n 的值指定为 4 并将 m 的值指定为 5 ,则 scanf 即可完成工作。

但是在打印时,当 i 的值为 0 且 j 为 0 时,它不会打印任何内容。

同时 a[0][1] 打印第一个输入,a[0][2] 连续打印第二个输入,因此打印时缺少最后一个输入 0。

请解释为什么要避免使用a[0][0]。


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.

您需要刷新输入缓冲区。或者在前面加一个空格%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)在这种情况下工作? http://www.c-faq.com/stdio/stdinflush.html

fflush仅为输出流定义。由于它对“刷新”的定义是完成缓冲字符的写入(而不是丢弃它们),因此丢弃未读输入不会有类似的含义fflush在输入流上。

建议阅读: c-常见问题解答 12.18 http://www.c-faq.com/stdio/scanfc.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C中的字符数组消隐 的相关文章

随机推荐