使用matlab将连接字符串打印到屏幕和文本文件

时间:2016-05-06 13:57:03

标签: matlab printf

这是一个非常基本的问题,但由于我是Matlab的新手,我很难找到一个好方法。我只想打印一些连接的字符串到屏幕和文本文件。 Matlab是"吃"然后 !!

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);

我还需要将finalStr保存到文本文件中。 我在这里失踪了什么?

2 个答案:

答案 0 :(得分:2)

函数strcat忽略空格。要执行此操作,请使用:

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

结果:

Line 1 
Line 2

编辑: 在"记事本"中的文本文件上写文本方式:

% Notepad needs \r also.
newline = sprintf('\n');
newlineNotepad = sprintf('\r\n');
strB = strrep(strA, newline, newlineNotepad);

答案 1 :(得分:0)

您还可以完全删除strcat的使用:

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