c - 我应该像介绍的那样使用 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;
}
解决方案
推荐阅读
- git - 如何使用本地 git checkout 进行变更跟踪
- python - Colab 中的“TypeError:'NpzFile' 对象不可调用”
- reactjs - 使用退格键清除输入字段时显示最后结果的搜索组件
- 3d - 如何使用 GET 字符串语法将 OBJ 文件的 URL 传递给 G.Viewer?
- kotlin - 奖励广告无效事件和 004 Kotlin 错误代码
- html - HTML Step 属性无法正常工作
- mysql - 我有 3 个表并且有关系,这是检索数据的最佳方式
- r - 避免在 glmnet::cv.glmnet 中计算截距
- file-conversion - 关于 MaxTract(将 pdf 转换为 LaTeX 的软件)的一些问题
- java - 在 Spring Boot 中,如何在 @WebMvcTest 期间从启动器启用 @ControllerAdvice