Working on homework in C Programming with Code::blocks for making a list of students with add, remove, sort and search capabilities, I wrote a function for searching students based on student code as follow :
void search_student(struct student students[],int n)
{
char temp_code[11];
int row = 0;
printf("Please enter the student code to search: ");
scanf ("%s", temp_code);
printf("\n#\tFirst_Name\tLast_Name\tStudent_Code\tAverage\n");
puts("------------------------------------------------------------------");
for (int i = 0 ; i < n ; i++)
{
printf("temp code= %s --- students[%d].first_name = %s\n", temp_code, i, students[i].student_code);
if (strcmp(temp_code, students[i].student_code) == 0 )
{
printf("%d\t%s\t\t%s\t\t%s\t%f\n",
i+1, students[i].first_name, students[i].last_named, students[i].student_code, students[i].average);
row = i + 1;
}
}
if (row == 0)
{
puts("\nThe Student Code does not exist!\n");
}
}
the output of first fprint in for loop showed the following output:
Please enter the student code to search: student0002
# First_Name Last_Name Student_Code Average
------------------------------------------------------------------
temp code= student0002 --- students[0].student_code = student0001
temp code= student0002 --- students[1].student_code = student0002
temp code= student0002 --- students[2].student_code = student0003
The Student Code does not exist!
it seems after first loop, strcmp adds a character to end of temp_code which causes wrong output!!!
I found that manipulating irrelevant parts of the code can solve this problem!! (for example removing row = i+1 after second printf in for loop) and of course using strncmp can work nice!! anyway I couldn't figure out why strcmp acts like this!!