Full disclosure, this is an assignment for a class I have to do. We have a program that checks if two words are anagrams. We are supposed to modify it so that we can enter the words as command lines in a program. For instance: (./a.out hello elloh: is an anagram... ./a.out hello world: Not an anagram).
Here is the original program:
#include <stdio.h>
#define N 26
int main()
{
char ch;
int letter_counts[N]= {0};
int i;
int count =0;
printf("enter a word: ");
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']++;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
printf("enter the second word: ");
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']--;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
for(i =0;i<N;i++)
if(letter_counts[i]==0)
count++;
if(count == N)
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
return 0;
}
Now here is what I have so far:
#include <stdio.h>
#define N 26
/*
This program is a modified version of anagram.c so that the words run as command-line arguments.
*/
int main(int argc, char *argv[])
{
if(argc != 3)
{
printf("Incorrect number of arguments");
return 0;
}
char ch;
int letter_counts[N]= {0};
int i;
int count =0;
//int k;
//for (k = 1; i < argc; i++)
//{
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']++;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']--;
}
//for(i =0;i<N;i++)
//printf("%d", letter_counts[i]);
for(i =0;i<N;i++)
if(letter_counts[i]==0)
count++;
int k;
int j;
for (k = 1; i < argc; i++)
{
for (j = 0; j < N; j++)
{
if (count == N)
{
printf("%s and %s are anagrams\n", argv[k], argv[k + 1]);
break;
}
else
printf("The words are NOT anagrams. \n");
}
}
if(count == N)
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
//}
return 0;
}
The output (if the number of arguments is correct) is always :
0000000000000000000000000
0000000000000000000000000
These are anagrams
What am I doing wrong here and what is the best way to go about this?
Thank you for any help I really appreciate it.