I am unable to understand what's wrong in this code.
16 views (last 30 days)
Show older comments
Write a function called char_counter that counts the number of a certain character in a text file. The function takes two input arguments, fname, a char vector of the filename and character, the char it counts in the file. The function returns charnum, the number of characters found. If the file is not found or character is not a valid char, the function return -1.
I am unable to pass 2 out of 4 assessment which includes 'Invalid input' and 'Non existent file'. What wrong it this code?
function charnum = char_counter(fname, character)
fid = fopen(fname, 'r');
x = 0;
if fid < 0 || ~ischar(character)
fprintf('-1');
return
end
lines = fgets(fid);
while ischar(lines)
for i = 1:length(lines)
if lines(i) == character
x = x + 1;
end
end
lines = fgets(fid);
end
charnum = x;
fclose(fid);
0 Comments
Answers (1)
Fangjun Jiang
on 30 Jun 2023
Edited: Fangjun Jiang
on 30 Jun 2023
if fid < 0 || ~ischar(character)
fprintf('-1');
charnum=-1;
return
end
1 Comment
Fangjun Jiang
on 30 Jun 2023
To avoid leaving fid un-closed, it is beter to separate the condictions
if ~ischar(character)
charnum=-1;
return
end
fid = fopen(fname, 'r');
if fid < 0
charnum=-1;
return
end
See Also
Categories
Find more on Signals 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!