首页 > 解决方案 > 我应该像介绍的那样使用 fflush 吗?有什么选择吗?

问题描述

所以。我是 C 编程新手。我听说不要在某处使用 fflush 并且想知道任何比 fflush 对于我的输入更干净和有用的替代方案。如果没有 fflush,fgets 将无法正常工作。

这个函数只是附加一个文件,employees.txt 与新员工的姓名和职业

#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;
}

标签: c

解决方案


推荐阅读