If the user enters one the passwords below, I will ask him about secret question, but I don't do it using if else...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
int main(void) {
char pass[SIZE];
char originalPass[SIZE] = "abcDEF123=!)";
printf("Password: ");
fgets(pass, sizeof pass, stdin);
printf("\n");
// if the user enters one the passwords bellow, I will ask him about secret Q
// but I don't do it using if else...
/*
bacDEF123=!)
acbDEF123=!)
abDcEF123=!)
abcEDF123=!)
abcDFE123=!)
abcDE1F23=!)
abcDEF213=!)
abcDEF132=!)
abcDEF12=3!)
abcDEF123!=)
abcDEF123=)!
*/
return 0;
}
CodePudding user response:
You could enter all the passwords into an array and use a for (or any other loop) loop to iterate through the array and compare each element to the originalPass
.
EDIT: Please dont use gets, use fgets instead
#define LENGTH //number of strings
char passwords[LENGTH][SIZE]= { //enter strings here };
int i =0;
while(i<LENGTH)
{
if( strcmp(passwords[i], originalPass) == 0)
{
// do something
}
i ;
}
CodePudding user response:
You can use a fuzzy comparison function:
/* return 0 if the strings compare equal,
1 if they compare equal with a single swap
-1 otherwise
*/
int fullycmp(const char *s1, const char *s2) {
int swap = 0;
size_t i = 0;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
if (len1 != len2)
return -1;
while (i < len && s1[i] == s2[i])
i ;
if (i < len - 1 && s1[i] == s2[i 1] && s1[i 1] == s2[i]) {
swap = 1;
i = 2;
}
while (i < len && s1[i] == s2[i])
i ;
return i == len ? swap : -1;
}
If you really must not use if
or else
, you can replace the if
statements above with while
statements:
int fullycmp(const char *s1, const char *s2) {
int swap = 0;
size_t i = 0;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
while (len1 != len2)
return -1;
while (i < len && s1[i] == s2[i])
i ;
while (i < len - 1 && s1[i] == s2[i 1] && s1[i 1] == s2[i]) {
swap = 1;
i = 2;
break;
}
while (i < len && s1[i] == s2[i])
i ;
return i == len ? swap : -1;
}
Also make sure you strip the newline with:
pass[strcspn(pass, "\n")] = '\0'; // strip the trailing newline