How to distinguish pressing cancel vs entering an empty string in inputdlg?
7 views (last 30 days)
Show older comments
I have an input dialog box that will reopen if an invalid name is entered (it will close if more than 5 attempts is made). It is asking for a name to create a file with.
I want the user to be able to press "cancel" or the "x" (windows close button) and have the program exit, but I also want the user to not type anything and press "ok" and have it count as an incorrect attempt and reopen the box.
However, the only way I found people saying to use this is to check if the input is empty, if it is to break. However, this does not distinguish between meaningfully enterring an empty string and pressing cancel/x.
Is there a way to do what I am trying to do?
Also, if there is a better way to write the code in general, please let me know. I am open to improvements and criticism. This is my first MATLAB script I've written. It's been a journey trying to learn the language/script (coming only from standard C).
Here is the snippet from my code:
while badFileName == true
attemptsLeft = num2str(5 - errorCounter);
outputName = inputdlg(['Please enter a file name. Do not use spaces! Attempts left: ' attemptsLeft],'Output File Creation');
if isempty(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters);
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
end
0 Comments
Accepted Answer
Matt J
on 14 Jun 2024
Edited: Matt J
on 14 Jun 2024
However, this does not distinguish between meaningfully enterring an empty string and pressing cancel/x.
It should. Hitting ok with nothing entered wouldn't return an empty result.
while badFileName == true
attemptsLeft = num2str(5 - errorCounter);
outputName = uiputfile('', "Please enter a valid file name. Attempts left: " + attemptsLeft);
if isnumeric(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters);
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
end
2 Comments
Matt J
on 14 Jun 2024
Also, thank you so much!!
You're quite welcome, but please Accept-click the answer to indicate that it produced a solution for you.
Is ther anything else I can improve on?
Looks good to me!
More Answers (1)
Catalytic
on 14 Jun 2024
You could also do this -
while badFileName == true
attemptsLeft = num2str(5 - errorCounter);
outputName = inputdlg(['Please enter a file name. Do not use spaces! Attempts left: ' attemptsLeft],'Output File Creation');
if isempty(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters)||isempty(outputName{1});
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
end
0 Comments
See Also
Categories
Find more on Downloads in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!