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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Downloads についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!