Creating a password checker using basic programming

23 vues (au cours des 30 derniers jours)
윤은 지
윤은 지 le 15 Oct 2021
Commenté : 윤은 지 le 28 Oct 2021
What I am trying to do here is to create a program to check whether the input is identical to set password by only using the basics.(if, for, while and such)
The program would need to ask for a password until a correct one is entered.
the code I intended to write was:
key = 'test1234'
x = input('Enter the password: ','s') ;
while strlength(x) ~= 6
if strlength(x) ~= 6
fprintf('\nInput = %s',x)
fprintf('\nPassword is incorrect.')
x = input('Enter the password: ','s')
else strlength(x) == 6
break
end
end
while x ~= key
if x ~= key
fprintf('\nInput = %s',x)
fprintf('\nPassword is incorrect.')
x = input('Enter the password: ','s')
else x == key
break
end
end
fprintf('Password is correct.')
the problem I faced at first was that the use of == function would only work if the key and the input had the same length. Otherwise then it would only pop an error, so I merely made it so that it would check for the length of the password first.
But then after entering 6 length input that is not identical to the desired key, the program would move on to the next criteria and thus pop another error when the next input isn't 6-long.
I am literally new to programming stuff so any help would be appreciated.

Réponse acceptée

Sahil Jain
Sahil Jain le 20 Oct 2021
From my understanding of the question, you want to create a basic password checker using basic programms constructs like "if" statements and "for/while" loops. You can make the following changes to your code to make sure it functions.
  1. Use a "string" (double quotes, "test1234") instead of a "character array" (single quotes, 'test1234') for your key. This is because using the "~=" operator with a "character array" returns an array of logical values instead of a scalar.
  2. The length and the value of the entered password need to be checked simultaneously. This can be done using the short-circuit OR operator.
The resulting code would be as follows.
key = "test1234";
x = input('Enter the password: ','s') ;
while strlength(x) ~= strlength(key) || x~=key
fprintf('\nInput = %s',x);
fprintf('\nPassword is incorrect.');
x = input('Enter the password: ','s');
end
fprintf('Password is correct.');
Normally, if "x" and "key" are of different lengths, the "~=" operator would throw an error. However, the short-circuit "||" operator would not evaluate the right side if the left side evaluates to "true" and so no error is thrown in this case.
  1 commentaire
윤은 지
윤은 지 le 28 Oct 2021
Hi, sorry for the late reply. Thanks for the help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by