#include "iostream"
#include "string"
#include <fstream>
#include <cctype>
using namespace std;
#define NO_OF_CHARS 256
bool checkAnagram(string a,string b);
// Function to print all pairs of anagrams
void findAllAnagrams(string str[], int n)
{
// loop for all strings from array
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
if (checkAnagram(str[i], str[j])) // check if two strings are anagrams
cout << str[i] << " is anagram of " << str[j] << endl; // print if strings are anagrams
}
// function to check whether two strings are anagram or not //
bool checkAnagram(string string1, string string2)
{
// Create two count arrays and initialize all values as 0
int count[NO_OF_CHARS] = {0};
int i;
for (i = 0; string1[i] && string2[i]; i++)
{
count[string1[i]]++;
count[string2[i]]--;
}
if (string1[i] || string2[i])
return false;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i])
return false;
return true;
}
int main()
{
string string_name;
ifstream file_stream;
int count = 0;
file_stream.open("PrideAndPrejudice.txt"); // open file to read. your filename
// while loop to count number of strings
while (getline(file_stream, string_name , ' '))
{
count++;
for (int i = 0, length = string_name.size(); i < length; i++)
{
string_name[i] = tolower(string_name[i]);
// check whether parsing character is punctuation or not
if (ispunct(string_name[i]))
{
string_name.erase(i--, 1); // if punctuation is found erase that character
length = string_name.size(); // reduce size of string
}
}
}
file_stream.close();
file_stream.open("PrideAndPrejudice.txt"); // open file again to point to start of file
string wordArr[count]; // create word array to store the list of words read from file
count = 0; // initialize count to 0
while (getline(file_stream, string_name , ' '))
{
for (int i = 0, length = string_name.size(); i < length; i++)
{
string_name[i] = tolower(string_name[i]); // convert uppercase to lowercase
// check whether parsing character is punctuation or not
if (ispunct(string_name[i]))
{
string_name.erase(i--, 1);
length = string_name.size();
}
}
wordArr[count] = string_name; // store word in array
count++;
}
findAllAnagrams(wordArr, count); // check all anagrams
file_stream.close(); // close file stream
return 0;
}
My code is giving no output, am I not reading in the file correctly?