简体   繁体   English

为什么scanf无法正常工作

[英]why doesn't scanf work properly

I want to input 16 characters in an array one by one... 我想在数组中一个接一个地输入16个字符...

#include<stdio.h>
void main(){
 int i,j;
 char a[4][4];
printf("Enter Values in array : ");
for ( i=0 ; i<=3 ; i++ )
{
for ( j=0 ; j<=3 ; j++ )
{
    printf("a[%d][%d] : ",i,j);
    scanf("%c",&a[i][j]);
}}
for ( i=0 ; i<=3 ; i++ )
{
for ( j=0 ; j<=3 ; j++ )
{
    printf("a[%d][%d] : %c\n",i,j,a[i][j]);
}}}

and the output is 输出是

a[0][0] : q
a[0][1] : a[0][2] : w
a[0][3] : a[1][0] : e
a[1][1] : a[1][2] : r
a[1][3] : a[2][0] : t
a[2][1] : a[2][2] : y
a[2][3] : a[3][0] : u
a[3][1] : a[3][2] : i
a[3][3] :

why cant I input in a[0][1],a[0][3] and so on....why are they being skipped... and also please tell a better method to make this work... 为什么我不能输入a [0] [1],a [0] [3]等等。...为什么它们被跳过...并且还请告诉一个更好的方法来使其工作...

scanf() leaves the newline characters in the input buffer which is consumed by the subsequent calls. scanf()将换行符留在输入缓冲区中,以供后续调用使用。

Tell scanf() to skip the whitespaces. 告诉scanf()跳过空格。

scanf(" %c",&a[i][j]); // Notice the space in the format string

The space in the format specifier makes scanf() ignore any white space characters before reading a character (for %c ) 格式说明符中的空格使scanf()在读取字符之前忽略任何空白字符(对于%c

this is the problem when taking character input in C Language. 这是使用C语言进行字符输入时的问题。 when we type a character and press ENTER key then the ASCII value of ENTER would become the value for next scanf. 当我们键入一个字符并按ENTER键时,ENTER的ASCII值将成为下一个scanf的值。

you are required to flush the stdin buffer, and for that you should write fflush(stdin). 您需要刷新标准输入缓冲区,为此,您应该编写fflush(stdin)。

 #include<stdio.h>

    void main(){

    int i,j;
    char a[4][4];
    printf("Enter Values in array : ");

    for ( i=0 ; i<=3 ; i++ )
    {
    for ( j=0 ; j<=3 ; j++ )
    {
        printf("a[%d][%d] : ",i,j);
        scanf("%c",&a[i][j]);
        fflush(stdin);// will clear the input buffer stdin

    }
    }
    for ( i=0 ; i<=3 ; i++ )
    {
    for ( j=0 ; j<=3 ; j++ )
    {
        printf("a[%d][%d] : %c\n",i,j,a[i][j]);
    }
    }
    }

The answer by KingsIndian explains the issue. KingsIndian的回答解释了这个问题。

As a solution I would use getchar() or getwchar() (see man 3 getchar). 作为解决方案,我将使用getchar()或getwchar()(请参见man 3 getchar)。 By reading a character ad a time you can: 通过一次阅读角色广告,您可以:

  1. check whether the character you read belongs to the type you are expecting (see ctype.h or wctype.h) 检查您读取的字符是否属于您期望的类型(请参阅ctype.h或wctype.h)

  2. discard the ones you don't want like blanks, CRs, LFs tabs and the likes. 丢弃不需要的内容,例如空格,CR,LF选项卡等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM