Hello all. I am writing a hangman game and have run across a problem. Basically, I am keeping track of the letters the user has entered to prevent the repeating of a letter. In the code I have, I can only check adjacent letters but that's it. So if the letter array is "aba" the second 'a' wouldn't be caught. Here is the function.
1 2 3 4 5 6 7
bool checkLetter(char letter[])
{
for(unsignedint index=0;index<strlen(letter)-1;index++) //loop only checks adjacent characters. Not sure how to check all
if(letter[index]==letter[index+1])
returnfalse;
returntrue;
}
EDIT:
the array to store the letters is char letter[26];
Get an array of 26 characters. For each character read in, scan through the entire array and see if it's been recorded there. If it's not, record it. If it has, then it's a duplicate.
A more complex but faster solution:
Get an array of 26 bools (in C, chars). For each character read it, check a space in the array that records information for *only* that character (example: make [0] record info for A/a, [1] for B/b, and so on). If the boolean is false, set it to true, and if it was true, it's a duplicate.
Ok got it to work. Here is the updated function. I would post the entire hangman code I wrote but it exceeds the limit. (My hangman pictures take up too much lines).
1 2 3 4 5 6 7 8 9
bool checkLetter(char letter[], unsignedint i) //variable i is the index of letter
{
for(unsignedint index=0;index<strlen(letter);index++)
if(index==i) //avoid comparing the character itself
continue;
elseif(letter[index]==letter[i])
returnfalse; //duplicate was found, so false is returned
returntrue; //duplicate wasn't found
}
Albatross, I followed your first suggestion so I think this is what you meant..