1

In the following code in my program:

do
    {
        printf("\nEnter records of student %d: \n", i++);
        printf("Name: ");
        fgets(record.name, sizeof(record.name), stdin);
        printf("\nAddress: ");
        fgets(record.address, sizeof(record.address), stdin);
        printf("\nClass Level: ");
        scanf("%d", &record.classlevel);
        printf("\nTelephone Number: ");
        scanf("%ld",&record.telephone);
        fwrite(&record, sizeof(record),1,fptr);
        printf("\n\nAdd another record? [y/n]: ");


    }while(getche()=='y');

When i see the output, It works fine for the first time

Enter records of student 1

Name: <some input>

Address: <some input>

Class Level: <some input>

Telephone Number: <some input>

Add another Record? [y/n]: <pressed Y>

Enter records of student 2

Name: < no cursor comes , cannot provide input here>

Address: <only can input here>

.

.

..... etc..

What's happening, Why am i not able to input Name after first iteration in the do...while loop. Is the getche() doing any problem?

Hoping your Help

Thanks in Advance

Community
  • 1
  • 1
cipher
  • 2,414
  • 4
  • 30
  • 54
  • 1
    This has been discussed a zillion times on SO. Basically scanf leaves newline char in the buffer which is passed as input to next call. You need to clear (flush) input buffer after each call to scanf. http://stackoverflow.com/questions/3640604/c-getchar-vs-scanf – fkl Nov 23 '12 at 16:48

1 Answers1

1

You need to fflush(stdin) at the beginning of your do{...}while because getche() leaves a newline in the input-buffer.

Kninnug
  • 7,992
  • 1
  • 30
  • 42
  • `fflush(stdin)` is undefined behaviour. Some implementations claim that `fflush`ing an input stream does what is expected, but I'd not recommend doing it even there. – Daniel Fischer Nov 23 '12 at 16:54
  • You're right, but I do recall solving similar problems that way. – Kninnug Nov 23 '12 at 17:00
  • Yes, it may work, but I'd rather not rely on it. My man page says "For input streams, `fflush()` discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.", but if I don't misremember, I tried it on `stdin` once and it didn't work. – Daniel Fischer Nov 23 '12 at 17:03
  • So, what else do you suggest @DanielFischer ? (It worked this time, though) – cipher Nov 23 '12 at 17:32
  • 1
    @cipher Usually, the old `int ch; while((ch = getchar()) != EOF && ch != '\n'); if (ch == EOF) { /* input error, stdin closed or corrupted, how to handle? */ }` loop is enough. If you may need to read multiple lines from the buffer, it gets hairy. – Daniel Fischer Nov 23 '12 at 18:20