C-在文件处理中未找到记录
我有这个C代码,其中,我遇到的问题是,我无法找到我想要的记录,使用文件处理它总是说没有找到结果。什么是使我的系统清晰工作并显示记录的正确方法C-在文件处理中未找到记录,c,C,我有这个C代码,其中,我遇到的问题是,我无法找到我想要的记录,使用文件处理它总是说没有找到结果。什么是使我的系统清晰工作并显示记录的正确方法 #include <stdio.h> #include <conio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <windows.h>
void loadMenu();
void addEmployee();
void searchEmployee();
bool found = false;
int choice;
FILE*myrec;
char Name[20],Age[20],IDnum[20],search[20];
void loadMenu(){
printf("[1]Add Employee\t[2]Search Employee\t[3]Exit\nChoice:");
scanf("%d", &choice);
}
void addEmployee (){
char ans;
do{
printf("Enter IDnumber:");
fflush(stdin);
gets(IDnum);
printf("Enter Name:");
fflush(stdin);
gets(Name);
printf("Enter Age:");
fflush(stdin);
gets(Age);
myrec = fopen ("record.txt","a+");
fprintf(myrec,"%s \t %s \t %s \n ",Name,Age,IDnum);
printf("Record Saved !");
printf("Do you want to add another record ? Y/N");
scanf("%s",&ans);
fclose(myrec);
}
while (ans=='Y'||ans=='y');
}
void searchEmployee(){
myrec = fopen("record.txt","a+");
printf("Enter Employee IDnumber:");
scanf("%s",&search);
while(!feof(myrec)){
fscanf(myrec,"%s %s %s",IDnum,Name,Age);
if (strcmp(search,IDnum)==0){
printf("IDnum: %s\n", IDnum);
printf("Name: %s\n",Name);
printf("Age :%s\n",Age);
found = true;
break;
}
}
if(!found) printf("No results.");
fclose (myrec);
}
int main(){
bool repeat = false;
do{
loadMenu();
switch(choice){
case 1:
addEmployee();
break;
case 2:
searchEmployee();
break;
case 3:
repeat = true;
break;
}
}while(!repeat);
getch();
}
#包括
#包括
#包括
#包括
#包括
#包括
void loadMenu();
无效雇主();
作废雇员();
bool-found=false;
智力选择;
文件*myrec;
字符名[20],年龄[20],IDnum[20],搜索[20];
void loadMenu(){
printf(“[1]添加员工\t[2]搜索员工\t[3]退出\n选择:”);
scanf(“%d”,选择(&C);
}
无效雇主(){
查尔安斯;
做{
printf(“输入IDnumber:”);
fflush(stdin);
获取(IDnum);
printf(“输入名称:”);
fflush(stdin);
获取(名称);
printf(“输入年龄:”);
fflush(stdin);
获得(年龄);
myrec=fopen(“record.txt”,“a+”);
fprintf(myrec,“%s\t%s\t%s\n”,名称、年龄、IDnum);
printf(“记录已保存!”);
printf(“是否要添加其他记录?是/否”);
scanf(“%s”、&ans);
fclose(myrec);
}
而(ans=='Y'| ans=='Y');
}
void searchEmployee(){
myrec=fopen(“record.txt”,“a+”);
printf(“输入员工ID号:”);
scanf(“%s”,搜索(&s);
而(!feof(myrec)){
fscanf(myrec,“%s%s%s”,IDnum,Name,Age);
if(strcmp(search,IDnum)==0){
printf(“IDnum:%s\n”,IDnum);
printf(“名称:%s\n”,名称);
printf(“年龄:%s\n”,年龄);
发现=真;
打破
}
}
如果(!find)printf(“无结果”);
fclose(myrec);
}
int main(){
布尔重复=假;
做{
loadMenu();
开关(选择){
案例1:
addEmployee();
打破
案例2:
searchEmployee();
打破
案例3:
重复=正确;
打破
}
}而(!重复);
getch();
}
我的代码怎么了?有很多错误
一些简单的例子:
“a+”
)模式下打开。此模式支持读取,但仍然很奇怪fscan()
。他们可能会失败永远不要打电话给fflush(stdin)-这是UB-见男人。另外,请正确格式化您的代码。比较
scanf(“%s”,&search)
vsfscanf(myrec,“%s%s%s”,IDnum,Name,Age)
。其中一个不会按您的预期编写结果。如何使用更好的语法修复代码?@PaulR-如何使用更好的语法公式?:(对于第一个:char ans[50];scanf(“%s”,ans);