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 vue (au cours des 30 derniers jours)
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

Réponses (2)

Walter Roberson
Walter Roberson le 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'
  2 commentaires
Kapil Dhanwani
Kapil Dhanwani le 23 Sep 2016
Yes I want digits only...no alphabets and no space so what changes I should make

Connectez-vous pour commenter.


Srishti Saha
Srishti Saha le 13 Mai 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

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by