Input in C. Scanf before gets. Problem
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!
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);
...
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
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#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.