Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c - 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("
 %s
", spaceLetters);
printf("Attempt Left: %d
", attemptLeft);
boolean start = T;
int userInput;


while (1)
{
  printf("
");
  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
", spaceLetters);
        printf("Attempt Left: %d
", attemptLeft);
        printf("
");  
                      
     }       
    
  }
  

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

  if(word == spaceLetters){
     break;
  }
 }
}
question from:https://stackoverflow.com/questions/65886595/break-loop-when-condition-match

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...