我正在尝试编写一个程序,该程序采用名称列表,对这些名称进行排序,并允许用户从该列表中搜索名称。程序可以编译,但是一旦用户输入“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(" %s", &userChoice);
while(userChoice == 'y')
{
printf("\n\n\nPlease try to search for a name: ");
scanf("%s", searchText);
if(!(binarySearchNames(nameList, NUM_OF_NAMES, searchText, &searchLocation)))
printf("\n\n\nThe name %s 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);
}