gpt4 book ai didi

c - 如何使用 fscanf 从文件中读取并查找与用户输入匹配的记录

转载 作者:行者123 更新时间:2023-11-30 16:43:50 24 4
gpt4 key购买 nike

我想读取用户输入并验证它是否与“user.txt”记录匹配,如果匹配则提示用户错误消息,但scanf读取的数据总是会变成随机的号码,这是代码。抱歉我的英语,因为我不是以英语为母语的人

                int day,month,year;
char name[15];


printf("Enter your name\n");
scanf(" %[^\n]s",name);
printf("Enter you birthday(dd/mm/yyyy)\n");
scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year);
printf("Enter your contact number (60-)\n");
scanf("%d",&contactNumber);
printf("Enter your postcode\n");
scanf("%d",&postcode);

char x [30];
int y,z,w,d;
int duplicateContactNum [15];
int checkSentinel=0;

filepointer=fopen("user.txt","r");
if(filepointer==NULL){
//Not exist,Print exception message
printf("Exception Occur: Error writing text into the text file");

}
while(!feof(filepointer))
{
fscanf(filepointer,"%s;%d/%d/%d;%d;%d\n",x,&y,&z,&w,&duplicateContactNum,&d);
if(strcmp(contactNumber,duplicateContactNum)==0)
{
checkSentinel++;
break;
}

}
if(checkSentinel!=0)
{
rewind(filepointer);
printf("You have entered a duplicated entry\n");
fclose(filepointer);
}
else
{
rewind(filepointer);
fclose(filepointer);
filepointer=fopen("user.txt","a");
fprintf(filepointer,"%s;%d/%d/%d;%d;%d\n",name,day,month,year,contactNumber,postcode);
fclose(filepointer);
}

最佳答案

您在初始格式字符串中有一个错误,并且您没有测试 scanf 调用的返回值,因此所有返回错误都没有警告您。

            printf("Enter your name\n");
if (1 != scanf(" %[^\n]",name)) { // no s after [] format
fprintf(stderr, "Error reading name\n");
return 1;
}
printf("Enter you birthday(dd/mm/yyyy)\n");
if (3 != scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year)) {
...
}
printf("Enter your contact number (60-)\n");
if (1 != scanf("%d",&contactNumber)) {
...
}
printf("Enter your postcode\n");
if (1 != scanf("%d",&postcode)) {
...
}

记住:始终测试输入功能

关于c - 如何使用 fscanf 从文件中读取并查找与用户输入匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44920681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com