I/O string

5 ビュー (過去 30 日間)
Hanna Dulay
Hanna Dulay 2019 年 12 月 3 日
コメント済み: Walter Roberson 2019 年 12 月 3 日
I'm having a difficulty on replacing the tag with the given replacement word on the given text file for the 3rd subfunction.
here is what I have done so far
function [] = ()
clc;clear
readstring = read_form('form.txt');
[tag,replacement] = read_sub_tag();
newstring = replace_tags(readstring,tag,replacement);
create_output('Tongue_Twister.txt',newstring)
end
function readstring = read_form(textfile)
readstring = []; %empty readstring
text=fopen(textfile,'r');
if text==-1 %Check if the file opened correctly
sprintf('File not correctly open')
else
while ~ feof(text) %to read until the end
txt=fgets(text); %read every single line
readstring=sprintf('%s\r',readstring,txt);
readstring=strcat(readstring);%concatenate the lines into string
end
end
fclose(text);
return
end
function [tag,replacement] = read_sub_tag()
tag = []; %empty tag
replacement = []; %empty replacement
sub_tag=fopen('sub.txt','r');
if sub_tag==-1 %check if the file opened correctly
sprintf('File not correctly opened')
else
while feof(sub_tag)==0
sub=fgetl(sub_tag);
[tag,replacement]=strtok(sub); %to create separate arrays for the tag and replacement
tag=lower(tag);
replacement=strtrim(replacement);
end
end
fclose(sub_tag);
return
end
function newstring = replace_tags(readstring,tag,replacement)
newstring = "";
r_s=lower(readstring);
i= strfind(r_s,tag);
tg=i+length(tag);
splitlines(readstring);
for final=readstring(i:tg)
newstring=replace(readstring,final,replacement);
end
return
end
function create_output('Tongue_Twister.txt';newstring)
name=fopen('Tongue_Twister.txt,''wt');
fprintf(name,newstring);
fclose(name);
end
  1 件のコメント
Walter Roberson
Walter Roberson 2019 年 12 月 3 日
while feof(sub_tag)==0
sub=fgetl(sub_tag);
[tag,replacement]=strtok(sub); %to create separate arrays for the tag and replacement
tag=lower(tag);
replacement=strtrim(replacement);
end
That code is throwing away all of the tags and replacement information, except for the very last one. Even then, in some circumstances you throw away the last one as well, as feof() is not guaranteed to be true when you have just positioned after the last newline in the file; in traditional POSIX file semantics, feof() would not be true in that situation, leading to an empty fget() result.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by