Fprintf not inserting new line correctly with /n
9 次查看(过去 30 天)
显示 更早的评论
I have a loop and part of it includes displaying text in the command window only, I don't need to export the string.
I've tried different positions of using /n in fprintf but I can't seem to get it to work properly. After the whole text string, I need a line break. I've also tried \r and \n together, but I get the same results. I assume I'm missing something obvious. I'm not quite sure where the /n is supposed to go.
Using disp and sprintf works as intended, as an example of what I want it do to.
% assign variable
InputFolders = [1 1 1];
% disp and sprintf works as intended
disp(sprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")"))
disp(sprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")"))
%%
% No \n included
fprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")")
fprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")")
%%
% \n on end - the \n is printed, presumably because I have %s at the start reading it as text
fprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")\n")
fprintf("%s","Length of input and output folders match (",num2str(length(InputFolders)),")\n")
%%
% \n at start - gives a new line, but after every part of text, not at the end of the string
fprintf("%s\n","Length of input and output folders match (",num2str(length(InputFolders)),")")
fprintf("%s\n","Length of input and output folders match (",num2str(length(InputFolders)),")")
0 个评论
采纳的回答
per isakson
2021-3-31
编辑:per isakson
2021-3-31
fprintf(formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and displays the results on the screen.
For every A1,A2,...,An the formatSpec should (typically) contain one Formatting Operator (or the formatSpec is reused).
Example
fprintf("%s\n","Length of input and output folders match (", "3" ,")")
The formatting operator, "%s\n", is reused three times: for "Length of input and output folders match (", for "3" and for ")" You intended (I guess)
fprintf( "Length of input and output folders match (%d)\n", 3 )
which outputs
Length of input and output folders match (3)
3 个评论
per isakson
2021-3-31
编辑:per isakson
2021-3-31
"Interesting that the disp and sprintf method doesn't work for you" Indeed it does. I firstly replaced (too save on line length) num2str(length(InputFolders)) by 3 (which didn't work). With "3" it works.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!