Variable charnum has an incorrect value. When testing with ' ' your solution returned 1 which is incorrect.
Show older comments
I had to write a function that counts the number of a certain character in a text file. 2 input arguments are requested: fname (char vector of the filename) and character (the char it counts in the file).
Output argument: the number of characters found. If the file is not found or character is not a valid char, the function return -1.
I've seen some answers here in the community forum but I'm just confused why my later part of the code doesn't seem to work. Will be highly pleased if anyone can debunk this silly mistake I'm making in my code:
function charnum = char_counter(fname,character)
fid = fopen(fname,'rt');
charnum=0;
if fid < 0 || ~ischar(character)
charnum = -1;
return
end
oneline = fgets(fid);
ln=length(oneline);
for i=1:ln
if oneline(i) == character
charnum=charnum+1;
end
end
fclose(fid);
Answers (0)
Categories
Find more on Argument Definitions 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!