Good afternoon ladies and gentlemen. I would like someone to take a look at my loop to help me find the error that I am making. The purpose of this program is to unscramble the user's input. for example if the user entered 'ftooabll' the program would print 'football'
Now, this only works for strings that are contained in the file wordlist. That being said, I would like this to repeat this search multiple times. Currently, the process is being repeated 7 times, but it only works on the first iteration. The code and sample input/output is below.
Thank you very much for your help.
(p.s. I have only been studying C for about a month, so please bear with me through this.)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMLOOP 6
void sort_string(char*);
int main()
{
char string[100];
int i, j = 0;
char string_1[100], string_2[100], string_3[100];
FILE* wordlist;
wordlist = fopen("wordlist.txt", "r");
while (j <= NUMLOOP) { // Start loop to ask for NUMLOOP different strings to search for in the wordlist
printf("Enter string:\n"); // Prompt user for string.
gets(string); // Place entered string into "string"
sort_string(string); // Call to function "sort_string" to alphabetize the characters in "string"
while (fgets(string_1, sizeof string_1 , wordlist) != NULL) // Begin loop to search wordlist for match & load wordlist into string_1
{
strcpy(string_2, string_1); // Copy string_1 into string_2 to save original format of word
sort_string(string_1); // alphabetize each string in the wordlist
int result = strcmp(string, string_1); // Compare entered string against the alphabetized wordlist
if (!result)
{
printf("%s", string_2); // If a match is found, print it.
}
}
++j;
}
return 0;
}
void sort_string(char *s)
{
int c, d = 0, length;
char *pointer, *result, ch;
length = strlen(s);
result = (char*)malloc(length+1);
pointer = s;
for ( ch = '!' ; ch <= '}' ; ch++ )
{
for ( c = 0 ; c < length ; c++ )
{
if ( *pointer == ch )
{
*(result+d) = *pointer;
d++;
}
pointer++;
}
pointer = s;
}
*(result+d) = '\0';
strcpy(s, result);
free(result);
}
Sample input/output:
(note: all data has been verified to be in the wordlist)
Enter string:
4132dcba
abcd1234
Enter string:
4132dcba
Enter string:
4132dcba
Enter string:
4132dcba
Enter string:
4132dcba
Enter string:
4132dcba
Enter string:
4132dcba