Anagram problems

440 views Asked by At

I'm new to this forum and would like to seek help. I'm trying to modify an anagram program based on code from http://www.sanfoundry.com/c-program-...ings-anagrams/. This time, however, I have used array pointers to obtain input from the user. I have also created a function "check_input" to ensure that the input consists of ONLY characters and excludes symbols(!, #, $). However, when I ran the program, it still accepts those symbols and does not break like I wanted it to. Please help.

Plus, I intend to make the program treat upper-case letters the same way as lower-case letters. Can this be achieved by using the "stricmp" function? If so, where should I place that function? Alternative methods are also appreciated.

Update: Sorry. I've added the check_input code at the bottom.

#include <stdio.h>
#include <ctype.h>
#include <string.h>


int test_anagram(char *ptrArray1, char *ptrArray2);
int check_input(char array1[], char array2[]);

int main()
{
char array1[100], array2[100];
char *pArray1, *pArray2;
int flag;

pArray1 = array1;
pArray2 = array2;

printf("Enter the first word: \n");
gets(pArray1);

printf("Enter the second word: \n");
gets(pArray2);

check_input(pArray1, pArray2);

flag = test_anagram(pArray1, pArray2);
if(flag == 1){
    printf("\"%s\" and \"%s\" are anagrams.\n", pArray1,    pArray2);
}else{
    printf("\"%s\" and \"%s\" are not anagrams.\n", pArray1, pArray2);
}

return 0;
}

int test_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;

while(array1[i] != '\0')
{
    num1[array1[i] - 'a']++;
    i++;
}

i = 0;
while(array2[i] != '\0')
{
    num2[array2[i] - 'a']++;
    i++;
}

for(i=0;i<26;i++)
{
    if(num1[i] != num2[i]){
        return 0;
    }
    return 1;
}


}

int check_input(char array1[], char array2[])
{
while(isalpha((int)array1) != 1){
    break;
}

while(isalpha((int)array2) != 1){
    break;
}
}
1

There are 1 answers

0
syntagma On

You haven't (yet) posted the full code of the check_input() function but one advice would be to validate the input when the user inputs every character.

You can do this using f.e. the getchar() function and checking if the inputted character is a letter, as well as converting it to the lowercase (or uppercase if you will).

You can do lowercase convertion like this:

#include <ctype.h>

// ...
tolower('A');