Write a function called digit_counter that takes the name of a text file as input and returns the number of digits (i.e., any of the characters, 0-to-9) that the file contains. If there is a problem opening the file, the function returns -1

1 view (last 30 days)
function[c]=digit_counter(filename)
fid=fopen(filename,'rt');
if fid<0
error('error opening file %s', filename);
end
A = char(fread(fid,inf)).';
c=length(A);
fclose(fid);
end

Answers (2)

Walter Roberson
Walter Roberson on 23 Sep 2016
Your code returns the number of bytes in the file. The requirements are that it return the number of digits in the file -- that is, the total number of occurrences of any of the characters '0', '1', '2', '3', '4', '5', '6', '7', '8', or '9'

Srishti Saha
Srishti Saha on 13 May 2018
A simple function as this would work:
function n = digit_counter(fname)
n = -1;
fid = fopen(fname,'r');
if fid >= 0
n = sum(isstrprop(fread(fid,inf,'char=>char'),'digit'));
fclose(fid);
end
end

Categories

Find more on Function Creation 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!