我想读取用户输入并验证它是否与“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);
}
答案 0 :(得分:0)
初始格式字符串中有一个错误,并且您没有测试 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)) {
...
}
调用的返回值,因此所有返回错误但您没有收到警告。
C5:H558
请记住:始终测试输入功能