Input in C. Scanf before gets. Problem

Dmitri picture Dmitri · Mar 2, 2010 · Viewed 24.2k times · Source

I'm pretty new to C, and I have a problem with inputing data to the program.

My code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
   int a;
   char b[20];

   printf("Input your ID: ");
   scanf("%d", &a);

   printf("Input your name: ");
   gets(b);   

   printf("---------");

   printf("Name: %s", b);   

   system("pause");
   return 0;
}

It allows to input ID, but it just skips the rest of the input. If I change the order like this:

printf("Input your name: ");
   gets(b);   

   printf("Input your ID: ");
   scanf("%d", &a);

It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!

Answer

IVlad picture IVlad · Mar 2, 2010

Try:

scanf("%d\n", &a);

gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.

Edit:

if the above doesn't work, try:

...
scanf("%d", &a);
getc(stdin);
...