I am currently working on a game in class but have some problems when printing and checking strings. Essentially it is hang man and I need to print the word as just _
(underscores) with spaces separating each underscore. I am just filling in a skeleton code and the code I had to fill in looks like:
initializeBlankString(const int numLetter, char revealedLetters[25])
{
int i;
for(i=0;i < numLetter; i++){
revealedLetters[i] = '_';
}
revealedLetters[numLetter - 1] = '\0';
}
printWithSpaces(char revealedLetters[25])
{
int i;
for(i=0;i<(strlen(revealedLetters));i++){
printf("%c ", revealedLetters[i]);
}
}
revealGuessedLetter(char word[], char revealedLetters[25], char guess)
{
int i, n = 0;
for(i=0;i<strlen(word);i++){
if (word[i] == guess){
revealedLetters[i] = guess;
n = 1;
}
}
return n;
}
checkGuess(char word[25], char revealedLetters[25])
{
if(word == revealedLetters)
return 1;
else
return 0;
}
I have tried lots of different things and I am unable to be successful. The problems would is when the word is something like unix it will show _ _ _ _ + r 6 _
instead of just _ _ _ _
I escaped I thought but it doesn't look like it.
Function calls look like this:
initializeBlankString(strlen(word), revealedLetters);
printWithSpaces(revealedLetters);
charRevealed = revealGuessedLetter(word, revealedLetters, guess);
won = checkGuess(word, revealedLetters);
solution:
void initializeBlankString(const int numLetter, char revealedLetters[25])
{
int i;
for(i=0;i < numLetter; i++){
revealedLetters[i] = '_';
}
revealedLetters[numLetter] = '\0';
}
void printWithSpaces(char revealedLetters[25])
{
int i;
for(i=0;i<(strlen(revealedLetters));i++){
printf("%c ", revealedLetters[i]);
}
}
int revealGuessedLetter(char word[], char revealedLetters[25], char guess)
{
int i, n = 0;
for(i=0;i<strlen(word);i++){
if (word[i] == guess){
revealedLetters[i] = guess;
n = 1;
}
}
return n;
}
int checkGuess(char word[25], char revealedLetters[25])
{
for(int i = 0; i < strlen(word);i++){
if(word[i] != revealedLetters[i])
return 0;
}
return 1;
}
The position for the final '\\0'
is miscalculated in initializeBlankString
:
revealedLetters[numLetter - 1] = '\0';
Should be:
revealedLetters[numLetter] = '\0';
There are many more problems with your code:
Modern C mandates function return types. void
for the first 2, int
for the last 2.
You cannot compare char arrays with if(word == revealedLetters)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.