- 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.
- The length and the value of the entered password need to be checked simultaneously. This can be done using the short-circuit OR operator.
Creating a password checker using basic programming
19 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Sahil Jain
2021-10-20
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.
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!