MATLAB Answers

0

How do I write a code to verify that the filename entered by the user ends in .txt?

Asked by Elaine Collins on 28 Nov 2018
Latest activity Commented on by Greg
on 28 Nov 2018
This is what I have so far.
filename = input('Enter your filename ending in .txt: ', 's');
s1 = '.txt';
s2 == 'filename'
tf == strcmp(s1,s2)
if tf == 0
filename = input('Enter your filename ending in .txt: ', 's');
end
Thanks!

  0 Comments

Sign in to comment.

1 Answer

Answer by Greg
on 28 Nov 2018
Edited by Greg
on 28 Nov 2018
 Accepted Answer

filename = input('Enter your filename ending in .txt: ', 's');
s1 = '.txt';
s2 == 'filename' % <-- I think you're confused on = versus == here
tf == strcmp(s1,s2) % <-- and here
if tf == 0
filename = input('Enter your filename ending in .txt: ', 's');
end
You can achieve this quite simply with:
filename = input(___);
while ~endsWith(filename,".txt")
filename = input(___);
end
endsWith was introduced in R2016b, and double quotes to create strings in R2017a.

  2 Comments

Sign in to comment.