im making a program that loads a collection of strings from a file. then the user need to search the keyword using a binarysearch, but im using strings in my program, how to make the program using array of characters? here's my code, thx before :)
#include <iostream>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
void sort(string array[], int len);
void binarySearch(string array[], int len, string searchItem);
void print(string array[], int len);
int main() {
int rows=0;
char filename[30];
string names[100];
ifstream fin;
string searchName;
cout << "Enter a filename: ";
cin >> filename;
fin.open(filename);
if (!fin) {
cout << "Error opening file.";
return 0;
}
while (getline(fin,names[rows])) {
rows++;
}
sort(names,rows);
print(names,rows);
cout << endl;
cout << "Enter a word to search it on the list: ";
cout << endl;
cin >> searchName;
binarySearch(names,rows,searchName);
fin.close();
return 0;
}
void sort(string array[], int len) {
int i, j;
string check;
for(i=1; i<len; i++) {
check = array[i];
for(j=i; j>=1 && (check < array[j-1]); j--) {
array[j] = array[j-1];
array[j-1] = check;
}
}
}
void print(string array[], int len) {
for(int i=0; i<len; i++) {
cout << array[i] << endl;
}
}
void binarySearch(string array[], int len, string searchItem)
{
int first = 0;
int last = len - 1;
int mid;
bool found = false;
while
(first <= last && !found)
{
mid = (first + last) /2;
if (array[mid] == searchItem)
found = true;
else if (array[mid] > searchItem)
last = mid -1;
else
first = mid + 1;
}
if (found)
cout << "you keyword is found : " << searchItem << " in data number : " << mid ;
else
cout << "Key word not found";
}