【发布时间】:2012-10-29 21:39:23
【问题描述】:
我一直在研究我在编程的第一学期学习过的所有内容。我有一个期末考试,所以我一直在尝试编写示例程序,结合我所学的一切准备。下面的程序应该从文件中读取名称,通过冒泡搜索对其进行排序,然后提示用户输入一个名称,二分搜索将查找该名称并告诉您此人是否为朋友。
我的问题是,当我输入名称时,只会提示我再次输入名称。没有输出。
请记住,这里的所有内容大部分都是我到目前为止所学到的(所以我不知道如何使用向量、指针等)。
#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;
}
}
【问题讨论】:
-
Searching a array of strings 的可能重复项
-
这也是我的问题,它已经纠正了一些问题,建议开始一个新问题。
-
在你的排序函数中,
for (int count = 1; count < (size - 1); count++)应该是for (int count = 1; count < size; count++); -
@jrok 这不会让我超出数组中的元素数量吗?
-
不,
count会小于size并且你永远不会访问索引 [count+1],所以没关系。
标签: c++ arrays sorting binary-search