名前のリストを取得し、それらの名前を並べ替え、ユーザーがそのリストから名前を検索できるようにするプログラムを作成しようとしています。プログラムはコンパイルされますが、ユーザーが名前を検索するために「y」を入力し、検索したい名前を入力すると、プログラムはフリーズします。
どんな助けにも感謝します!
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define NUM_OF_NAMES 8
#define NAME_SIZE 5
void printNames(char names[][NAME_SIZE], int size);
void bubbleSortNames(char names[][NAME_SIZE], int last);
bool binarySearchNames(char list[][NAME_SIZE], int end, char target[], int *location);
int main()
{
char nameList[NUM_OF_NAMES][NAME_SIZE] = {"Bob", "Sue", "Jake","Rod", "Jon",
"Ash", "Deb", "Kay"};
char searchText[NAME_SIZE];
char userChoice;
int searchLocation;
printf("\n\n\nLIST BEFORE SORTING\n");
printNames(nameList, NUM_OF_NAMES);
bubbleSortNames(nameList, NUM_OF_NAMES);
printf("\n\n\nLIST AFTER SORTING\n");
printNames(nameList, NUM_OF_NAMES);
printf("\n\n\nWould you like to search for a name? (y/n) ");
scanf(" %c", &userChoice);
while(userChoice == 'y')
{
printf("\n\n\nPlease try to search for a name: ");
scanf("%c", searchText);
if(!(binarySearchNames(nameList, NUM_OF_NAMES, searchText, &searchLocation)))
printf("\n\n\nThe name %c was not found.\n", searchText);
else
{
printf("\n\n\nThe name %s was found at location %d!", searchText,
searchLocation);
}
}
printf("\n\n\nThank you for using this program.\n\n\n");
return 0;
}
/********************************
Prints the names from the array.
********************************/
void printNames(char names[][NAME_SIZE], int size)
{
int index;
for(index = 0; index < size; index++)
puts(names[index]);
return;
}
/*******************************
Sorts the names from the array.
*******************************/
void bubbleSortNames(char names[][NAME_SIZE], int last)
{
char temp[NAME_SIZE];
int current;
int walker;
for(current = 0; current < last; current++)
{
for(walker = last; walker > current; walker--)
{
if(strcmp(names[walker], names[walker - 1]) < 0)
{
strncpy(temp, names[walker - 1], sizeof(temp) - 1);
strncpy(names[walker - 1], names[walker], sizeof(names[walker - 1])
- 1);
strncpy(names[walker], temp, sizeof(names[walker]) - 1);
}
}
}
return;
}
/*********************************
Searches for names to be printed.
*********************************/
bool binarySearchNames(char list[][NAME_SIZE], int end, char target[], int* location)
{
int first = 0,
last,
mid;
last = end;
while(first <= last);
{
mid = (first + last) / 2;
if(strcmp(target, list[mid] > 0)
first = mid + 1;
else if(strcmp(target, list[mid]) < 0)
last = mid - 1;
else
first = last + 1;
}
*location = mid + 1;
return (strcmp(target, list[mid]) == 0);
}