Anagram program

I'm having trouble understanding why this program doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#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;
  if (anagram("sjkf","")) 
   {cout << "true"; }

  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;
}
line 12: The ; terminates the for loop.

Here's a simpler version:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool anagram(string s1, string s2) 
 {  char    c;
    size_t  pos;
    
    for (unsigned i=0; i<s1.length(); i++)
    {   c = s1[i];   
        pos == s2.find(c);
        if (pos == string::npos)
            return false;       //  Can't be an anagram
        s2.erase (pos);         //  Remove from s2
    }
    return s2.empty();
}


Topic archived. No new replies allowed.