【发布时间】:2012-01-13 16:58:30
【问题描述】:
这个程序的主要目的是从文件中读取多达 100 个名称,使用冒泡排序进行排序,然后通过二进制搜索搜索输入的名称。
似乎一切正常,但当我输入列表中的名称时,没有任何反应,只是提示我再次输入名称。
在猫王的列表中说出一个名字。系统提示我输入名称。我输入猫王。我应该收到猫王是你的朋友。没有发生。任何帮助表示赞赏。
#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;
}
}
【问题讨论】:
-
根据答案修复问题不是一个好主意,因为它几乎使每个答案都无效并使问题无用(因为那里 is 修复后没有问题)。除非更改只是装饰性的,否则您应该提出另一个问题,如果不再相关,则删除此问题。
-
好的,我将开始一个新问题。
标签: c++ arrays search binary-search