0

I try to write a code that you set a password and than set a limit of tries, which is the variable mistakes, and input different string to test if my guess and my password matches

The problem is, my variable, mistake, its value changes into "0" when the program goes into the for-loop even though I didn't change it's value in the loop.

my code is below

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char password[6];
    gets(password);
    int mistake = 0;
    scanf("%d\n", &mistake);
    char guess[6];
    int i = 0;
    int k = 0;
    int count = 0;
    printf("%d\n", mistake);

    for(i = 0; i<mistake; i++)
    {
        gets(guess);
        printf("%d", mistake);
        for(k = 0; k<6; k++)
        {
            if(guess[k] != password[k])
            {                
                if(i == mistake-1){
                    printf("you were electrocuted\n");
                    return 0;
                }
                else{
                    printf("wrong password\n");
                    break;
                }
            }
            else
                count++;
        }
        if(count == 6){
            printf("correct\n");
            return 0;
        }
    }

    return 0;
}

I expect the value never changes inside the loop or out side the loop, however it's value always changes into 0. I check the variable, mistake, its value before the loop and inside the loop.I want to know why it changes and what should I do. I thought about if it's the problem about gets(), but I don't see anything that works for me.

Jack C
  • 1
  • 1
  • 3
    @ack C It seems the call of gets changes the variable mistake. Do not use gets. It is unsafe and is not supported by the C Standard. Either use scanf or fgets. – Vlad from Moscow Nov 12 '22 at 11:25
  • 1
    There is no `gets` function in C. Who is telling you to use it? Don't listen to that guy. – n. m. could be an AI Nov 12 '22 at 11:26
  • 1
    My guess? Your input for `guess` is equal to or longer than six characters. Remember that a six-element character array only can keep *five* character strings, to fit the null-terminator. This is what makes `gets` so [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) that is was removed from the C language specification. – Some programmer dude Nov 12 '22 at 11:27
  • I changed the length of array "guess" to 7, and it works, thanks , I think I'll just use scanf("%[^\n]%*c") next time, thank you – Jack C Nov 12 '22 at 11:35
  • 2
    `scanf` is no better than `gets` unless you specify a length limit your the input string. – Gerhardh Nov 12 '22 at 11:41
  • so I should always use getchar() if its about a string or a char? – Jack C Nov 12 '22 at 11:56
  • `scanf("%6s", ...)` should be fine, unless you want to use spaces. Then I rather recommend `fgets`. – Some programmer dude Nov 12 '22 at 11:56

0 Answers0