tags:

views:

571

answers:

4

Hi!

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!

+1  A: 

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);
...
IVlad
Hm. I've tried scanf("%d\n", but it doesn't seems to be working. After I input ID, I just dont see program doing anything else.
Dmitri
Wow! Thanks! That worked flawlessly! Thanks for advice about fgets. Will surely use it!! Thank you!
Dmitri
A: 

You might find the answers to this question helpful

http://stackoverflow.com/questions/2360183/fgets-from-stdin-problems-c/2360236#2360236

John Knoeller
+1  A: 

scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:

// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character

// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
AndiDog
Awesome!! Thank you very much!
Dmitri
bta
You present both options as if they had equal footing, but `scanf` is just so hard to use properly that it's much better to avoid using it entirely (see the comp.lang.c FAQ link). Just go with option 2.
jamesdlin
A: 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
        int a;
        char b[20];
        printf("Input your ID: ");
        scanf("%d", &a);
        getchar();
        printf("Input your name: ");
        gets(b);
        printf("---------");
        printf("Name: %s", b);
        return 0;
}



Note: 
  If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function. 

  If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
muruga