I am working on a program that will read a list of words from a file. For each word, I have to build a key which is basically the word with all of its letters sorted (i.e. dorw is the key for word). I need to build an array of all the keys sorted and an array of the primary words. Then, I need to go through array and find the duplicated keys and corresponding words. The output should look something like this:
pots stop
from form
lead deal
Right now, my program goes through the list and it rearranges the letters but it is not in alphabetical order. Please help me get on the right track.
#include <iostream>
#include <fstream>
using namespace std;
char read (char *, int);
char arrayCopy(char* , int& );
void getKeys(char*, int& );
void bubbleSortKeys (char * , int );
void findDuplicates(char* ,char* , int& );
char** read(const char* fileName, int& count)
{
ifstream countingStream(fileName);
// first count them
count = 0;
while (true)
{
char line[100];
countingStream.getline(line, 100);
if (strlen(line) == 0)
{
break;
}
count += 1;
}
countingStream.close();
ifstream readingStream(fileName);
char** words = new char* [count];
for (int index = 0; index < count; ++index)
{
char line[100];
readingStream.getline(line, 100);
words[index] = strdup(line);
cout << line << std::endl;
}
readingStream.close();
return words;
}
char** arrayCopy(char* words[], int& count)
{
char** keyArray = new char* [count];
for (int index = 0; index < count; ++index)
{
keyArray[index] = strdup(words[index]);
}
return keyArray;
}
void getKeys(char* keys[], int& count)
{
int length=0;
for (int keyIndex = 0; keyIndex < count; ++keyIndex)
{
length =strlen(keys[keyIndex]);
bubbleSortKeys(keys[keyIndex], length);
cout << keys[keyIndex] <<endl;
}
}
void bubbleSortKeys (char *array , int count)
{
char tempHold;
for (int pass = 0; pass < count - 1; pass++)
for (int compare = 0; compare < count - 1; compare++)
if (array[compare - 1] > array[compare])
{
tempHold = array[compare - 1];
array[compare - 1] = array[compare];
array[compare] = tempHold;
}
}
void findDuplicates(char* keys[],char* words[], int& count)
{
for (int keyIndex = 1; keyIndex < count; ++keyIndex)
{
if (strcmp(keys[keyIndex -1], keys[keyIndex])==0)
{
cout << keys[keyIndex] << " " << words[keyIndex]<< endl;
cout << keys[keyIndex-1] << " " << words[keyIndex-1]<< endl;
}
}
}
void printArray(char* keys[],char* words[], int& count)
{
cout <<" Keys array" << endl;
for (int keyIndex = 0; keyIndex < count; keyIndex++)
cout << keys[keyIndex] << endl;
}
int main ()
{
int wordCount;
char** words = read("words.txt",wordCount);
char** keys = arrayCopy(words,wordCount);
getKeys(keys,wordCount);
findDuplicates(keys,words,wordCount);
printArray(keys,words,wordCount);
return 0;
}