Search code examples
cscanfstring-comparisonc-strings

break loop when condition match


This is a word guessing game. For example, hello is given as h___o and the user must guess the letters.

I set a condition on my loop but don't know why it is not breaking the while loop.

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

int main()
{
char word[] = "hello";
int length = strlen(word);
int check;

char spaceLetters[length];
int i, j;
spaceLetters[0] = word[0];
char *dash = "_";

for (i = 1; i < length; i++)
{
  strncat(spaceLetters, dash, 1);
}
int attemptLeft = length;
printf("\n %s\n", spaceLetters);
printf("\t\t\tAttempt Left: %d\n", attemptLeft);
boolean start = T;
int userInput;


while (1)
{
  printf("\n");
  printf("Enter Letter:");
  scanf("%c", &userInput);

for loop for checking entered letter is true or not

  for (j = 1; j < length;j++)
  {
     if (word[j] == userInput)
     {
        spaceLetters[j] = word[j];
        printf("%s\n", spaceLetters);
        printf("\t\t\tAttempt Left: %d\n", attemptLeft);
        printf("\n");  
                      
     }       
    
  }
  

this is my break loop condition when hello == hello break loop

  if(word == spaceLetters){
     break;
  }
 }
}

Solution

  • Strings are represented by arrays/pointers. They need to be compared using string library. Replace

    if ( word == spaceLetters )
    

    with

    if ( strcmp ( word, spaceLetters ) == 0 )
    

    You'll also need to add #include <string.h>.