I have this functions , and i am trying to search in an array in a struct. Now I cant understand where my mistake is, but I believe that is, at the part where function is defined, where I try convert the player country into lowercase.( which in the file holds names of country). when I run the program, and I enter the country name the program just stops and crashes after I enter the name i want to search for.
Anyone can help me? Thank you .
#define NAME_LENGTH 50
#define NUM_PLAYERS 200
struct player_champ
{
char player_country[NAME_LENGTH];
};
int search_player_by_country( struct player_champ ptr_player[] , char asked_name[NAME_LENGTH], int lines_got);
int main (void)
{
struct player_champ player_info[NUM_PLAYERS] = { { 0 } };
char asked_country[NAME_LENGTH]= {0};
fflush(stdin);
printf("\nEnter the name of the country you want to search for.\n\n>>>");
fgets(asked_country, sizeof(asked_country)-1, stdin);
asked_country[strlen(asked_country)-1] = '\0';
search_player_by_country ( player_info, asked_country, num_lines_read);
int search_player_by_country( struct player_champ ptr_player[] , char asked_country[NAME_LENGTH], int lines_got)
{
char temp_asked_country[NAME_LENGTH], temp_country_name[NAME_LENGTH];
int i,k,z=0,j,counter=0;
// there is a part of the code here that converts what user entered to lower case as well.
for (i = 0 ; i < lines_got; i ++)
{
k=0;
/* while (ptr_player[i].player_country)
{
temp_country_name[j] = tolower (ptr_player.player_country);
j++;
}*/
for (k = 0 ; k < lines_got; k ++)
{
temp_country_name[k] = tolower (ptr_player[k].player_country);
k++;
}
temp_country_name[k] = '\0';
if (strstr(temp_country_name, temp_asked_country) != NULL)
{
print_info( ptr_player[i]);
}
}
}
This code is totally wrong:
for (k = 0 ; k < lines_got; k ++)
{
temp_country_name[k] = tolower (ptr_player[k].player_country);
k++;
}
k
twice -- in the loop header and in the body. temp_country_name
string, but the parameter to tolower()
is an entire string. Aren't you getting a warning from the compiler saying that the parameter to tolower()
is the wrong type (it expects a char
, you're giving it a char*
)? i
. This loop should just iterate over characters. Try this:
for (k = 0 ; ptr_player[i].player_country[k]; k ++)
{
temp_country_name[k] = tolower (ptr_player[i].player_country[k]);
}
ptr_player[i]
is the player from element i
in the array. player_country[k]
is character k
in that string. So ptr_player[i].player_country[k]
is the k'th character in the i'th player's country.
There are probably other problems in your code, I haven't tried to find them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.