Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read two characters consecutively using scanf() in C

I am trying to input two characters from the user t number of times. Here is my code :

int main()
{
    int t;
    scanf("%d",&t);
    char a,b;

    for(i=0; i<t; i++)
    {
        printf("enter a: ");
        scanf("%c",&a);

        printf("enter b:");
        scanf("%c",&b);
    }
    return 0;
}

Strangely the output the very first time is:

enter a: 
enter b:

That is, the code doesn't wait for the value of a.

like image 990
coder_r Avatar asked Oct 22 '25 20:10

coder_r


1 Answers

The problem is that scanf("%d", &t) leaves a newline in the input buffer, which is only consumed by scanf("%c", &a) (and hence a is assigned a newline character). You have to consume the newline with getchar();.

Another approach is to add a space in the scanf() format specifier to ignore leading whitespace characters (this includes newline). Example:

for(i=0; i<t; i++)
{
    printf("enter a: ");
    scanf(" %c",&a);

    printf("enter b: ");
    scanf(" %c",&b);
}

If you prefer using getchar() to consume newlines, you'd have to do something like this:

for(i=0; i<t; i++)
{
    getchar();
    printf("enter a: ");
    scanf("%c",&a);

    getchar();
    printf("enter b:");
    scanf("%c",&b);
 }

I personally consider the former approach superior, because it ignores any arbitrary number of whitespaces, whereas getchar() just consumes one.

like image 183
Filipe Gonçalves Avatar answered Oct 25 '25 11:10

Filipe Gonçalves