3

This is a very basic question, but since I'm new to Matlab, I'm struggling to find a good way to do so. I just want to print some concatenated strings to screen and to a text file. Matlab is "eating" the \n !!

str1 = sprintf('Line 1\n');
str2 = sprintf('Line 2\n');
finalStr = strcat(str1,str2);
% Print on screen
fprintf('%s',finalStr );
% Result: Line 1Line 2. What happened to the \n ?? !!!!

% Print on file
[curPath,name,ext] = fileparts(mfilename('fullpath'));
infoPath = fullfile(curPath,'MyFile.txt');
fid = fopen(infoPath,'w'); % Write only, overwrite if exists
fprintf(fid,finalStr);
fclose(fid);

I also need to save finalStr to a text file. What I'm missing here?

3
  • try %\n before the 1 Commented May 6, 2016 at 14:01
  • also double-check this mathworks.com/matlabcentral/answers/… Commented May 6, 2016 at 14:02
  • From the documentation for strcat: For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form feed. You have a trailing newline. Use horzcat instead. Commented May 6, 2016 at 14:03

2 Answers 2

2

The function strcat ignores white spaces. In order to perform this operation, use:

finalStr = [str1, str2];
fprintf('%s',finalStr );

result:

Line 1 
Line 2

Edit: To write the text on a text file in a "Notepad" way:

% Notepad needs \r also.
newline = sprintf('\n');
newlineNotepad = sprintf('\r\n');
strB = strrep(strA, newline, newlineNotepad);
Sign up to request clarification or add additional context in comments.

9 Comments

It prints correctly on screen now, but not on the text file.
the reason is that I used the name finalstr and not finalStr. I updated my answer accordingly, it should work now.
I'm sing the correct names. In the text file the resulting text does not consider the \n.
@Pedro77 your fprintf call is not correct. Also, don't use notepad to view your file.
@Padro77, as excaze mentioned, use some other program such as Interner browser, notepad++ or wordPad to view that it does work for files as well
|
0

You could also remove the use of strcat completely:

fprintf('%s%s',str1, str2);

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.