Search Program on this blog

Thursday 27 August 2015

Write a function called letter_counter that takes the name of a text file as input and returns the number of letters (i.e., any of the characters, a-to-z and A-to-Z) that the file contains. HINT: You can use the built-in function isletter. If there is a problem opening the file, the function returns -1. WARNING: if you use the ‘w’ flag with fopen, as opposed to ‘r’, you will overwrite the file.

function num = letter_counter(filename)
%Input filename is a text file
%Output num is a number of letters
s=0;
fid = fopen(filename,'rt');
if fid < 0
    num=-1;
    return;
end
oneline = fgets(fid);
while ischar(oneline)
    l=isletter(oneline);
    s=s+sum(l);
    fprintf('%s',oneline) % display one line
    oneline = fgets(fid);
end
num=s;
fprintf('\n');
fclose(fid);

1 comment:

  1. how about the problem with digit_counter,please help me.

    ReplyDelete