I am having trouble with the stdin buffer, I'd appreciate any insight, I have this function which accepts user input for last name
void lastName(int *counter, User *pt) {
for (int i = *counter; i < (*counter + 1); i++) {
pt[i].lastName = calloc (MAX_LENGTH, sizeof(char));
printf("Enter Last Name: ");
fgets(pt[i].lastName, MAX_LENGTH, stdin);
strtok(pt[i].lastName, "\n");
}
}
I also have this function that accepts user input for ID
void id(int *counter, User *pt) {
char num[MAX_LENGTH];
long temp;
for (int i = *counter; i < *counter + 1; i++) {
printf("Enter the ID of %s: ", pt[i].firstName);
fgets(num, MAX_LENGTH, stdin);
strtok(num, "\n");
temp = strtol(num, NULL, 10);
pt[i].id = (int) temp;
}
}
This is how I am calling them in main
lastName(&counter, pt);
id(&counter, pt);
If i enter a last name which is very long, it gets cut and displayed to MAX_LENGTH but the fgets for the ID gets skipped, otherwise it works fine. I am wondering as to how my fgets is working in this case? MAX_LENGTH is 10. I tried clearing my buffer with while(getchar() != '\n'); and it works but I have to press enter twice.
Enter First Name: Test
Enter Last Name: Williamsamsmases
Enter the ID of Test: Would you like to enter a User?(Y/N):N
fgets
will read everything it can until the destination is full. The rest of the input remains in the input buffer and, so the nextfgets
call reads what has been left behind. – Pablofflush(stdin)
is undefined behavior. You cangetchar
until\n
encountered. stackoverflow.com/questions/7898215/… – Eugene Sh.stdin
is not a seek-able stream, you cannot usefseek
withstdin
– Pablo