0

I am trying to concatenate three lines (I want to leave the lines as is; 3 rows) from Shakespeare.txt file that shows:

To be,
or not to be:
that is the question.

My code right now is

fid = fopen('Shakespeare.txt')
while ~feof(fid)
a = fgets(fid);
b = fgets(fid);
c = fgets(fid);
end
fprintf('%s', strcat(a, b, c))

I'm supposed to use strcat and again, I want concatenated and leave them as three rows.

2
  • You can put in the form of a string array is that what you want? Commented Nov 22, 2020 at 5:41
  • 1
    You already have the three lines in three separate variables. What result do you want exactly? A cell array of these lines? A string array? Commented Nov 22, 2020 at 12:32

1 Answer 1

1

One method of keeping the rows separate is by storing the lines of the text file in a string array. Here a 1 by 3 string array is used. It may also be a good idea to use fgetl() which grabs each line of the text file at a time. Concantenating the outputs of fgetl() as strings may also be another option to ensure the they do not get stored as character (char) arrays. Also using the \n indicates to line break when printing the strings within the array String_Array.

fid = fopen('Shakespeare.txt');
while ~feof(fid)
    
String_Array(1) = string(fgetl(fid));
String_Array(2) = string(fgetl(fid));
String_Array(3) = string(fgetl(fid));
end

fprintf('%s\n', String_Array);

Output result:

Ran using MATLAB R2019b

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.