Charnum Char_counter help please
1 次查看(过去 30 天)
显示 更早的评论
Hi - for those familiar with this assignment.. any help appreciated -
second test is failing saying returning 1.. im not sure if it should return -1 or 0 for this and not sure if i have attempted to fix it correctly either way.. here is what i have..
function charnum = char_counter (fname, character)
total = 0;
fid = fopen(fname, 'r');
if fid < 0 || ~ischar(character) || numel(character) > 1;
charnum = -1;
return
end
oneline = fgets(fid);
for ii = oneline(1:end);
if ii == character;
total = total + 1
end
charnum = total;
end
fclose(fid);
end
1 个评论
Walter Roberson
2020-9-3
Note: you also have one of the very common bugs. If the file open works, but the parameter is not a scalar character, then your code leaves the file open when it returns.
回答(1 个)
Walter Roberson
2020-9-3
Your code is only reading one line from the file, instead of reading all lines from the file.
2 个评论
Walter Roberson
2020-9-4
No, fgets() returns a character vector, and when you
for ii = oneline(1:end)
that is the same as
for ii = oneline
which in turn executes by setting ii to each element of the vector oneline in turn. (That is valid code in itself.)
So you are looping testing one character at a time from the line you read in. And you have suggested modifying the code so that each time you locate a copy of the character of interest, you replace the content of oneline with the content of the next line of the file. But remember the same character can occur more than once per line, so you would not want to be doing that. And it wouldn't work anyhow: when you start a for loop, MATLAB takes a copy of all of the variables involved in the for statement so any modifications to those variables will not affect the for loop.
You should be instead switching to have two layers of loop. The outer loop should be concerned with reading full lines until there is nothing left in the file. The inner loop should be concerned with proceeding character by character through the line that was read.
(Or, you know, you could vectorize counting the characters so you only had the outer loop...)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!