필터 지우기
필터 지우기

How to read a list of strings in a txt file?

조회 수: 11 (최근 30일)
Benson Gou
Benson Gou 2020년 9월 17일
댓글: Star Strider 2020년 9월 17일
Dear All,
I need to read a txt file which contains a list of names with different lengths. Here is my txt file:
mynames:
OAKFIELD
5556_T
ROLLINS
......
I need to read those names to store them in a string array MyNames. MyNames should be like below:
MyNames = [
'OAKFIELD'
'5556_T'
'ROLLINS'
......
];
Here is my code:
fid = fopen(FileName, 'r');
if fid < 0, error('Cannot open file'); end
while KKK < 30000 % Infinite loop
s = fgets(fid);
if ischar(s)
MyNames = [MyNames; s];
else % End of file:
break;
end
end
But what I got is Not correct. MyNames is an array having 10 coulmns and shows as
'CHSTRSVC←↵'
'5556_T'←↵'
'ROLLINS←↵'
...

채택된 답변

Star Strider
Star Strider 2020년 9월 17일
Unless I am missing something, ‘KKK’ is never incremented inside the while loop, so it will in fact be infinite.
If you are actually using ‘KKK’ as a counter (and therefore incrementing it), this could work:
MyNames{KKK} = s;
That creates a cell array, and while that can create additional steps required to recover its contents later, it could be an effective approach.
A better approach could be readtable. The first variable would be the names, and you could simply ignore the others.
.
  댓글 수: 4
Benson Gou
Benson Gou 2020년 9월 17일
편집: Benson Gou 2020년 9월 17일
I used data = sscanf(s, '%s %s'), and got the right cell array MyNames:
{'OAKFIELD'} {'OAKFIELD'} {'5556_T'} {'ROLLINS'} {'ROLLINS'} {'STETSON'} ...
Thanks a lot for all of you.
Benson
Star Strider
Star Strider 2020년 9월 17일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by