Quite a simple program:
int main (void)
{
int i = 0, length=0;
char password[] = SECRET;
char guess[10];
for (i=0; i<3; i++){
printf( "Enter the password: " );
fgets (guess, 10, stdin );
length=strlen(guess);
guess[length]='\0';
if(strcmp( guess, password ) == 0 ){
printf("\aYou got it right!\n" );
return 0;
}
else printf("You wrote %s Incorrect guess\n\n", guess);
}
puts("Sorry, you're all out of guesses");
return 0;
}
But it doesn't work.
Even in the bizarre situation where I can get the program to say: "You guessed 'black'. Sorry, the password was 'black'" Thought there might be some issue with some hidden character, blank space, garbage information or whatever throwing off the string comparison, but I can't seem to find what it is!
If you learn to use the debugger, you would probably see that the string returned by fgets()
includes the newline character, which doesn't match the string you compare to.
And what is the point of this code:
length=strlen(guess);
guess[length]='/0';
First of all, I can only assume you meant \0
instead of /0
. And second, strlen()
works by locating the null terminator. So what's the point of finding the terminator and then writing a terminator at the same location?