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!
scanf
doesn't consume the newline and is thus a natural enemy offgets
. Don't put them together without a good hack. Both of these options will work:scanf("%d", &a);
can't read the return, because%d
accepts only decimal integer. So you add a\n
at the beginning of the nextscanf
to ignore the last\n
inside the buffer.Then,
scanf("\n%s", b);
now can reads the string without problem, butscanf
stops to read when find a white space. So, change the%s
to%[^\n]
. It means: "read everthing but\n
"scanf("\n%[^\n]", b);
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.
Try:
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:
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
For explanation (isaaconline96@gmail.com);
The
scanf
function removes whitespace automatically before trying to parse things other than characters.%c
,%n
,%[]
are exceptions that do not remove leading whitespace.gets
is reading the newline left by previousscanf
. Catch the newline usinggetchar();
https://wpollock.com/CPlus/PrintfRef.htm