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 (최근 30일)
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

답변 (2개)

Walter Roberson
Walter Roberson 2016년 9월 23일
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 2018년 5월 13일
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

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by