c中的字符数组消隐

标签 c string whitespace scanf

代码

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   

错误

如果我将 n 的值设为 4 并将 m 设为 5 ,scanf 就可以完成工作。

但是当 i 的值为 0 且 j 为 0 时打印时它不会打印任何东西。

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

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

最佳答案

以前的 scanf 调用在输入缓冲区中留下 \n 字符,该字符与按 EnterReturn< 时的输入一起/kbd> 键。 scanf("%c",&a[i][j]); 在第一次迭代时读取 \n

您需要刷新输入缓冲区。在 scanf

中的 %c 之前放置一个空格
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);  

注意: Will fflush(stdin) work in this case?

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 for fflush on input streams.

推荐阅读: c-faq 12.18 .

关于c中的字符数组消隐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24512820/

相关文章:

ruby - 在 ruby​​ 的字符串中使用方法返回

c - 为结构数组元素(字符串)分配内存

php - HTML - 换行符被解释为空白字符

c - C中带有Pointer Point的结构的深拷贝

c - 如何正确修改以下 "switch"语句以获得预期的输出值

c - OpenCL 内核仅部分写入输出缓冲区

XmlSchema 空白崩溃 : What happens to multiple whitespaces?

c++ - 方法不占用 long long int 值显示错误

c# - String.Empty在字符串末尾的“为什么”

c - 如何使用scanf读取空格