1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//function Prototypes
void nameSort(string friendArray[], int ARRAY_SIZE);
//function to display names from file
void displayNames(string friendArray[], int counter);
//function to binary search for name in file/array
//How do i return a string?? I got the following code from web searches
int searchName(string friendArray[], int ARRAY_SIZE, string result);
int main()
{
const int ARRAY_SIZE = 200; //declare array size
string friendArray[ARRAY_SIZE];//array of 200 strings
ifstream fileIn; //create file object
int counter = 0;
string choice;
string result; //variable to hold the search result
fileIn.open("myFriends.dat");//open the file
if(fileIn.fail())//test to see if file opened
{
cout<<"Check to see if file is in same directory ";
cout<<"as the .cpp file."<<endl;
}
while(getline(fileIn, friendArray[counter]))
{
counter++;
}
//call function to sort array
nameSort(friendArray, ARRAY_SIZE);
//display sorted names to screen with function
displayNames(friendArray, ARRAY_SIZE);
//call to search function
searchName(friendArray, ARRAY_SIZE, result);
cout<<friendArray[counter]<<" is my friend."<<endl;
system("Pause");
return 0;
}
//sort function
void nameSort(string friendArray[], const int ARRAY_SIZE)
{
bool swap;
string temp;
do
{
swap = false; //set flag to false
for(int counter = 0; counter < (ARRAY_SIZE - 1); counter++)
{
if(friendArray[counter] > friendArray[counter + 1])
{
temp = friendArray[counter];
friendArray[counter] = friendArray[counter + 1];
friendArray[counter + 1] = temp;
swap = true;
}
}//close for loop
}while(swap);
}//end of function
//display names function
void displayNames(string friendArray[], const int ARRAY_SIZE)
{
for(int index = 0; index < ARRAY_SIZE; index++)
cout<<friendArray[index]<<endl;
}
//binary search function
int searchName(string friendArray[], const int ARRAY_SIZE, string result)
{
int first = 0;
int last = (ARRAY_SIZE - 1);
int middle;
int position = -1;
string name;
bool found = false;
cout<<"Please enter a name or END to quit.";
cin>>name;
while(!found && first <= last && name != "END")
{
middle = (first + last) / 2;
if(friendArray[middle] == result)
{
found = true;
position = middle;
}
else if(friendArray[middle] > result)
last = (middle - 1);
else
first = (middle + 1);
}
return position;
}
|