0

so today I made a program that basically gets the right password from the user. It works well with integers but when I rewrite the code for working with strings it isn't working. I have tried many different ways but nothing works. can anyone help me?

#include <stdio.h>

#include <stdlib.h>

int main() {

  char Guess[8];
  char Password[] = "password";
  int Guesscount = 3;
  int Granted = 1;

  while (Guess != Password && Granted == 1) {
    if (Guesscount > 0) {
      printf("Enter password: ");
      scanf("%s", Guess);
      Guesscount = Guesscount - 1;
      if (Guess != Password && Guesscount > 0) {
        printf("Wrong Password, you have %d try left.\n", Guesscount);
      }
    } else {
      Granted = 0;
    }
  }

  if (Granted == 0) {
    printf("Denied");
  } else {
    printf("Granted");
  }
  return 0;

}

2 Answers2

1

To compare two strings in C use the strcmp(str1, str2), it compares two strings character by character. If the strings are equal, the function returns 0.

Instead of this Guess != Password use this strcmp(Guess , Password) == 0.

AimenZer
  • 86
  • 1
  • 10
0

You cannot compare strings with == and != operators in C. For that purpose use strcmp() function which is defined in string.h header file.

That was the reason integers were working but string weren't. You can say that you cannot compare arrays with those equality operators.

Also, you are using scanf() function to take user input with format specifier "%s", which isn't very good, you should put a limit, for an example in your case "%8s". Also, to store 8 characters long password you need to make Guess at-least 9 character long.

Once, password was denied and Guesscount is > 0, then use memset() to clear Guess so that it can read new data.

Final Code Should Be:

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

int main() {
  char Guess[9];
  memset(Guess, 0, 9);
  char Password[] = "password";
  int Guesscount = 3;
  int Granted = 1;

  while (strcmp(Guess, Password) != 0 && Granted == 1) {
    if (Guesscount > 0) {
      printf("Enter password: ");
      scanf("%8s", Guess);
      Guesscount = Guesscount - 1;
      if (strcmp(Guess, Password) != 0 && Guesscount > 0) {
        printf("Wrong Password, you have %d try left.\n", Guesscount);
        memset(Guess, 0, 9);
      }
    } else {
      Granted = 0;
    }
  }

  if (Granted == 0) {
    printf("Denied");
  } else {
    printf("Granted");
  }
  return 0;

}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23