r/C_Homework • u/Barbonetor • May 24 '19
C problems with fgets and null input
/r/learnprogramming/comments/bsk5vl/c_problems_with_fgets_and_null_input/
3
Upvotes
1
u/Fransiscu May 24 '19
add a getchar(); after the scanf for the menu choice.
while(menu>-1){
printf("Insert choice: \n");
printf("1) Add employee.\n");
printf("2) List employees.\n");
printf("3) Delete employees.\n");
scanf("%d", &menu );
getchar(); // this
switch (menu) {
case 1:
addEmployee();
break;
case 2:
listEmployee();
break;
case 3:
deleteEmployee();
break;
default:
printf("Exiting..\n" );
}
} getchar is supposed to "eat" the enter character that you insert when you try to select the right option, so it's like you just entered 2 values instead of 1.
This comes from my first year programming 1 class so I hope the reasoning is correct. The solution surely works though.
happy coding!
1
u/Barbonetor May 24 '19
Thanks to everyone, as you pointed out printf("\n"); and fgets(); doesn't do well together
anyway i solved it by adding a getchar(); before every fgets(); and it worked fine!