So. Im new to C programming. I've heard not to use fflush somewhere and would like to know any alternatives that are way more clean and useful that fflush for my inputs. Without fflush, fgets would not work properly.
This function is just to append a file, employees.txt with the new hire's Name and Occupation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char hireName[20];
char hireRole[20];
char hireSalary[20];
float salaryF;
char endProgram[10];
printf("Ah.. its time again? Who did you hire this time? and whats their salary?\n");
while (1) {
/* Grabs Hire Name */
printf("Name: ");
fgets(hireName, 20, stdin);
fflush(stdin);
/* Grabs Hire Occupation */
printf("Occupation: ");
fgets(hireRole, 20, stdin);
fflush(stdin);
/* Grabs Hire's Salary */
printf("Salary: ");
fgets(hireSalary, 20, stdin);
fflush(stdin);
/* Wants to know if it should continue another hire (RESTARTS PROGRAM) */
printf("Continue? Y/Yes N/No: ");
fgets(endProgram, 5, stdin);
/*
* salaryF turns hireSalary from a char to a float type
* removes breakline from variables (endProgram, hireName, hireRole)
*/
salaryF = strtof(hireSalary, NULL);
endProgram[strcspn(endProgram, "\n")] = 0;
hireName[strcspn(hireName, "\n")] = 0;
hireRole[strcspn(hireRole, "\n")] = 0;
fflush(stdin);
//printf("Demo - Name: %s | Occupation: %s | Salary: %f | endProgram: %s\n", hireName, hireRole, salaryF, endProgram);
/* Opens employees.txt and appends the hire's name and the hire's occupation to the file! */
FILE * fEMPLOY = fopen("employees.txt", "a");
fprintf(fEMPLOY, "\n%s, %s", hireName, hireRole);
fclose(fEMPLOY);
if (strcmp(endProgram, "N") == 0 || strcmp(endProgram, "n") == 0 || strcmp(endProgram, "no") == 0 || strcmp(endProgram, "No") == 0) {
break;
} else {
continue;
}
}
return 0;
}