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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With