sps
sps

Reputation: 2730

Why isn't scanf( ) waiting for input from keyboard?

I have below C code.

#include<stdio.h>

int main()
{
    //Declaring structure book.
    struct book
    {
            char name;
            float price;
            int pages;
    };

    struct book b[5];

    int i;
    //Below loop takes the info if 5 books from user
    for (i=0; i<5; i++)
    {
            printf("Enter name, price, and pages: ");
            fflush( stdin );
            scanf("%c%f%d",&b[i].name,&b[i].price,&b[i].pages);
    }
        return 0;
}

However when I compile and run, something strange happens.

-bash-4.1$ ./a.out
Enter name, price, and pages: A 23 34
Enter name, price, and pages: B 34 54
Enter name, price, and pages: Enter name, price, and pages: C 56 78
Enter name, price, and pages: -bash-4.1$

You can see that when i = 2, scanf() does NOT wait for keyboard. Then when i = 3, scanf() waits for keyboard input. Again in i=4, scanf() does NOT wait for keyboard input.

I guess I have used

fflush(stdin);

in the correct place. I don't want the return key to be in the buffer in the next scanf().

To debug, i tried not to use fflush(stdin) and see what heppens. But even without the fflush(stdin), same thing happens when i run the program. So I guess fflush(stdin) is not causing this problem.

Please anyone point out, where my program is going wrong?

Thanks.

Upvotes: 0

Views: 598

Answers (1)

user3920237
user3920237

Reputation:

The C11 standard explains how %c works:

§7.21.6.2/8 Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.

As such, the linefeed produced by the enter key is consumed by %c. You can fix this by adding a space before %c:

§7.21.6.2/5 A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

Your code becomes scanf(" %c%f%d",&b[i].name,&b[i].price,&b[i].pages);.


Note that fflush should not be used here.

§7.21.5.2/2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

Upvotes: 4

Related Questions