dimanche 29 mars 2015

Comparing strings from files

I'm having a bit of problem. I want the program to search the file and if it matches with the input of the user, then the program will show "hello" and if not, it will show "bye". These outputs are just for testing purposes. Back to the problem. When it reaches the line of comparing, the program crashes. Now I'm clueless on how to solve the problem. I'm asking someone to help me please and thanks in advance. Below is a snippet of the code:



int CaseFunc();
int CaseFunc(){
FILE *memFile;
char memberfname[28];
char memberlname[28];
char ffname[28];
char flname[28];
char code;
struct PersonalInfo array[1000];
int memberage;
int menuANS;
int members;
int i;
members = 0;


printf("Enter your answer here: ");
scanf(" %d", &menuANS);

switch (menuANS){
case 1:

system("cls");


printf("Enter code: ");
scanf(" %c", &code);
do {

printf("Enter First Name: ");
scanf("%s", memberfname);
printf("Enter Last Name: ");
scanf("%s", memberlname);
printf("Enter Age: ");
scanf("%d", &memberage);

if ((memFile = fopen("TheCarDepot Members.txt", "a+")) == NULL){ //If the file path is incorrect, an error message is displayed
fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect
return;
}

fprintf (memFile, "%s %s %d", memberfname, memberlname, memberage);
fprintf (memFile, "\n");
fclose(memFile);
printf("\n\n");
printf ("*%s %s is now a member of TheCarDepot Team.*\n", memberfname, memberlname);




printf("Enter code: ");
scanf(" %c", &code);
}
while (code != 'x');

break;

case 2:
if ((memFile = fopen("TheCarDepot Members.txt", "r")) == NULL){ //If the file path is incorrect, an error message is displayed
fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect
return;
}

//while the file is opened and not at the end, the strings are stored into variables which forms an array of strings
for (members = 0; members < 200; members++) {
if (fscanf(memFile, "%s %s %d", memberfname, memberlname, &memberage) == 3) //Reads the contents of the file
break;
array[members].fname = strdup(memberfname);
array[members].lname = strdup(memberlname);
array[members].age = memberage;
}
fclose(memFile);

printf("Enter your first name: ");
scanf("%s", ffname);
printf("\n");

if (strcmp(array[members].fname, ffname) == 0){
printf ("hello");
}

else if (strcmp(array[members].fname, ffname) != 0){
printf ("bye");
}

break;

Aucun commentaire:

Enregistrer un commentaire