Reputation: 11
I am trying to find out if two string inputs are an anagram. The program has to ignore white spaces, punctuation, and numbers.
I have a function that validates each character in the input stream. When I run the program, it puts two white spaces after I input the first string. It also gives the wrong output.
#include <iostream>
#include <bits/stdc++.h>
#include <string>
#define No_of_chars 26
using namespace std;
const int SIZE = 26;
int count1[No_of_chars]={0};
// finds the strings are anagram
bool areAnagram(string str1, string str2)
{
// Get lengths of both strings
int n1 = str1.length();
int n2 = str2.length();
// If length of both strings is not same, then they cannot be anagram
if (n1 != n2)
return false;
// Sort both the strings
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Compare sorted strings
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;
}
// validate each character in the input string
void validateCharacter(string sentence)
{
char ch;
int count = 0;
cin.get(ch);
while(ch >= ' ' && count < SIZE)
{
if (isalpha(ch))
{
cin.ignore();
}
sentence=ch;
count++;
cin.get(ch);
}
}
int main()
{
string s1;
string s2;
cout<< "Csci Anagram Strings Program"<<endl;
cout << "enter something ->";
validateCharacter(s1);
cout << "enter something ->";
validateCharacter(s2);
if(areAnagram(s1, s2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each other";
return 0;
}
Getting wrong output:
Csci Anagram Strings Program enter something ->kkk enter something ->kkk The two strings are not anagram of each other
Upvotes: 0
Views: 630
Reputation: 799
You're missing a return true;
at the end of your areAnagram
function.
Upvotes: 2