I'm trying to get multiple consecutive user inputs, which will later be printed. It works fine as long as you don't input a string longer than the boundary, but when you do input something longer it overflows into the next input. For example, this code:
printf("Enter student's first name:\t");
char nameF[20];
scanf("%20s", nameF);
printf("Enter student's last name:\t");
char nameL[20];
scanf("%20s", nameL);
printf("Enter student's ID Number:\t");
char id[9];
scanf("%9s", id);
printf("Enter student's e-mail:\t");
char mail[26];
scanf("%26s", mail);
Results in this:
Enter student's first name: 01234567890123456789012345
Enter student's last name: Enter student's ID Number: 0123456789012345
Enter student's e-mail:
First: 01234567890123456789
Last:
ID Number: 012345678
E-mail: 9012345
I skipped over the print function for the sake of not having a wall of code. If you want to see that as well, let me know and I'll add it.
It should be noted that I tried fgets()
, with very similar results. If I replace each scanf()
line with fgets(var, sizeof(var), stdin);
, I get this:
Enter student's first name: 01234567890123456789012345
Enter student's last name: Enter student's ID Number: 0123456789012345
Enter student's e-mail:
First: 0123456789012345678
Last: 9012345
ID Number: 01234567
E-mail: 89012345
When I inserted getchar()
after the scanf()
statements, it ignored the overflow input, but still skipped over the next scan. I have tried throwaway input variables, and I've looked into other input methods, but couldn't seem to find anything to help. I'm sure this is a pretty simple fix for someone with experience, but I'm only a couple of weeks into learning C, so I don't know much beyond pointers and structs.
I can almost guarantee somebody will find a duplicate of this - they always do - but I did search around, for about a solid hour, and I didn't find anything that worked.
Thanks in advance for any help you can give me.
EDIT: I understand why the input is overflowing into the next one. It saves the first x characters, and the rest remains in the buffer and is entered into the next input scan.
I guess the more narrowed down question would be: How can I clear or divert the input buffer so that if the user inputs extra characters they won't remain in the buffer?