-3

I'm trying to debug this program but can't seem to find the bug with this program. Every 2 letter word is considered an anagram and every word with more than 2 letters is considered not an anagram.

#include <string>
#include <iostream>
using namespace std;

// Postcondition: the return value is true if s1 and s2 are anagrams
//   of each other 
bool anagram(string s1, string s2) 
 {
  string temp = s2;
  int i;

  for (i = 0; i < s1.length(); i++);
   {
    // invariant: temp is s2 with first copy of chars 0..i-1 
    //            of s1 removed 
    string newtemp = "";
    bool found = false;

    if (temp.length()==0) 
     {return false;}

    for (int j = 1; j < temp.length(); j++) 
     {
      if (!found && (s1[i] = temp[j])) 
        found = true;
      else 
        newtemp = newtemp + temp[j];
     };

    // assert: newtemp is temp with first occurrence of s1[i] removed
    temp = newtemp;

  };
  return (temp.empty());
}


int main() {
  string str1, str2;

  cout << "Enter two strings: ";
  cin >> str1 >> str2;

  if (anagram(str1,str2))
    cout << "The strings are anagrams!\n";
  else
    cout << "The strings are NOT anagrams.\n";
  return 0;
}
OmG
  • 18,337
  • 10
  • 57
  • 90
H.C
  • 9
  • 3
  • 8

1 Answers1

1

The algorithm to find an anagram is as follows ::

  1. Sort the string
  2. Compare the string.

Using STL C++11 you can implement the bool anagram function in couple of lines.

bool anagram (string s1, string s2)
{
      std::sort(s1.begin(), s1.end());
      std::sort(s2.begin(), s2.end());
      return s1 == s2;
}