Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How do I output data from a txt file?

조회 수: 3 (최근 30일)
John Jamieson
John Jamieson 2020년 11월 3일
마감: MATLAB Answer Bot 2021년 8월 20일
Let me explain, I want to take these messages from a .txt file:
Congratulations!
Way to go!
You're amazing!
Fantastic!
Wow!
So far I have this code:
function [asciifromfile] = getPhrase ()
g=rndInt(1,5);
fileID=fopen('CSE101lab5Congrats.txt',r);
asciifromfile=fread(fileID);
end
I want it to display one of the messages, depending on whether or not g=a number between 1 or 5. For example, if g=1, output Congragulations!

답변 (1개)

Aalali
Aalali 2020년 11월 4일
Hello John
Here is the modified version of your function to read one line from the file each time and store it to retrive it later:
function [txtLines] = getPhrase()
fileID = fopen('CSE101lab5Congrats.txt'); % open the text file
i = 1;
while ~feof(fileID) % while not reaching the end of file
asciifromfile = fgetl(fileID);% use fget1 to read a line from the text file
txtLines{i,1} = asciifromfile;% store each line from the file in a cell
i = i+1;
end
fclose(fileID);
end
Then, to call it:
[txtLines] = getPhrase();
g = randi(5)
disp(txtLines{g})
And here is an output example:
g = 4
Fantastic!
Hope this would help.
  댓글 수: 1
Rik
Rik 2020년 11월 4일
If you want to dynamically select any of the lines:
disp(txtLines{randi(end)})
This code will select any of the lines, even if there are more than 5.

이 질문은 마감되었습니다.

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by