基本上,该程序的目的是从文件中读取多达100个名称,使用冒泡排序,然后通过二进制搜索来搜索输入的名称。

除了输入列表中的名称时,其他所有操作似乎都没有问题,只是提示我再次输入一个名称。

在Elvis Presley的列表中说一个名字。系统提示我输入一个名称。我输入Elvis Presley。我应该收到猫王Elvis Presley是你的 friend 。没有发生。任何帮助表示赞赏。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void bubblesort(string[], const int);
void search(string[], const int);
int sub = 0;

int main()
{
 const int maxsize = 100;
 string friendArray[maxsize];

 ifstream friends;
 friends.open("myFriends.dat");

 while (sub < maxsize && getline(friends, friendArray[sub]))
   sub++;


 bubblesort(friendArray, sub);
 search(friendArray, maxsize);


 system("pause");
 return 0;
}



void bubblesort(string *array, const int size)
{
    bool swap;
    string temp;

    do
    {
        swap = false;
        for (int count = 1; count < (size - 1); count++)
        {
            if(array[count-1] >array[count])
            {
                temp = array[count-1];
                array[count-1] = array[count];
                array[count] = temp;
                swap = true;
            }
        }
    }
    while(swap);

}

void search(string *array, int size)
{
    int first = 0;
    int last = size - 1;
    int middle;
    string name;
    bool friends = false;

    do
    {
     cout<<"Please enter a name or END to terminate:";
     cin>>name;
    }
    while(!friends && first <= last && name != "END");
    {
        middle = (first + last) / 2;
        if (array[middle] == name)
            {
                friends = true;
                cout<<array[middle]<<" is my friend."<<endl;
            }
        else if (array[middle] > name)
            last = middle - 1;
        else
            last = middle + 1;
    }
}

最佳答案

search()函数中,do { } while; { }构造存在缺陷。它会编译,但不会执行您想要的操作。我进行了一些更改并重新排列了您的代码,以使其更有意义。

void search(string *array, int size)
{
    string name;

    for (;;)
    {
        cout<<"Please enter a name or END to terminate:";
        getline(cin, name);
        if (name == "END") break;

        int first = 0;
        int last = size - 1;
        bool friends = false;

        while (!friends && first <= last)
        {
            int middle = (first + last) / 2;
            if (array[middle] == name)
            {
                friends = true;
                cout<<array[middle]<<" is my friend."<<endl;
            }
            else if (array[middle] > name)
                last = middle - 1;
            else
                first = middle + 1;
        }
    }
}

int main () // test the search() function
{
    string array[] = { "bird", "cat", "dog", "horse", "loon", "zebra" };
    search(array, 6);
}

所以,这对作业有太多帮助吗?我应该删除它吗?

10-06 12:03