I am writing a CRUD program in C and at one point the user is asked to input an employee's code, which was previously stored in an array called "codes" in an employee registration section of the program, in order to register an employee's vehicle. The program should only continue if the user input is identical to an element of the codes array. Both user input and elements of the array are properly formatted, so there should be no differences other than the actual code.
I debugged by trying the value 1234 for the employee's code, which is successfully stored in the codes array, then I tried registering a vehicle by typing 1234, but the function I wrote that does the checking always return 0, so I'm thinking there is a flaw in the logic.
Variables:
char codes[100][256];
char owner[256];
Function to check if user input is indeed in any element of the array codes, returns 1 if it finds a match, or 0 at the end.
int checkOwner(char t_code[])
{
for (int i = 0; i < indice; i)
{
if(!strcmp(t_code, codes[i])) {
return 1;
}
}
return 0;
}
Input processing:
do {
printf("Type owner's code: ");
fgets(owner, sizeof(owner), stdin);
owner[strcspn(owner, "\n")] = '\0';
if(!checkOwner(owner))
printf("No employee with that code, try again.\n");
} while(!checkOwner(owner));
CodePudding user response:
I think the "logic flaw" stands in the for statement:
for (int i = 0; i < indice; i)
From the logic I see you want to go through all the codes you actually registered. However, at each iteration you would like to go to the next "line", but you only update i
by one.
for (int i = 0; i < indice; i =256)
should solve the problem hopefully, though I think at this point the condition i < indice
will cause problems (you could then use a second variable to count the "line number")
for (int i = 0, j = 0; j < indice; i =256, j)
I would also explicitly say:
if(strcmp(t_code, codes[i]) == 0)