How to distinguish pressing cancel vs entering an empty string in inputdlg?
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Matt J
2024-6-14
编辑:Matt J
2024-6-14
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 个评论
Matt J
2024-6-14
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!
更多回答(1 个)
Catalytic
2024-6-14
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!