sprintf before fprintf breaks newline

조회 수: 2 (최근 30일)
V E
V E 2016년 6월 23일
댓글: V E 2016년 6월 23일
I'm creating a string using sprintf before writing it into a file. I'm using sprintf because i have to insert content at the beginning after parsing all data.
Here is my problem, the newlines are completely broken. Some codes:
debut = sprintf(['Total tout benchmark : (miss ratio : %.2f%%)\n'...
'État des n-1 lignes dans l''ensemble (total : %s)\n'],100*misses/(misses+hits),...
char(nf.format(sum(sets))));
debut = strcat(debut, sprintf('%s\t%.2f%%\t(%s)\n', s{1}, tab_percent(1), char(nf.format(sets(1)))));
debut = strcat(debut, sprintf('%s\t\t%.2f%%\t(%s)\n', s{2}, tab_percent(2), char(nf.format(sets(2)))));
file = fopen('output.txt', 'wt');
fprintf(file, '%s', debut);
And the output:
Total tout benchmark : (miss ratio : 1.31%)
État des n-1 lignes dans l'ensemble (total : 1 490 360 487)modified 36.54% (544 629 216)owned 0.14% (2 106 818)
As you can see, the first line break is ok, but not the second nor the third. I tried with \n\n, but it didn't solve the problem. However, adding \n at the beginning of each line seems to do the trick, but for me, it's the same as \n\n :
debut = sprintf(['Total tout benchmark : (miss ratio : %.2f%%)\n'...
'État des n-1 lignes dans l''ensemble (total : %s)\n'],100*misses/(misses+hits),...
char(nf.format(sum(sets))));
debut = strcat(debut, sprintf('\n%s\t%.2f%%\t(%s)\n', s{1}, tab_percent(1), char(nf.format(sets(1)))));
debut = strcat(debut, sprintf('\n%s\t\t%.2f%%\t(%s)\n', s{2}, tab_percent(2), char(nf.format(sets(2)))));
gives the following output:
Total tout benchmark : (miss ratio : 1.31%)
État des n-1 lignes dans l'ensemble (total : 1 490 360 487)
modified 36.54% (544 629 216)
owned 0.14% (2 106 818)
Any idea why it acts like this and how to make newline works with only one \n? Thanks for your help.
edit: if it helps, I'm using matlab R2015b.

채택된 답변

Guillaume
Guillaume 2016년 6월 23일
편집: Guillaume 2016년 6월 23일
The problem has nothing to do with sprintf but with your usage of strcat. As per the documentation, "for character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form feed".
Simply replace strcat by normal concatenation (or another sprintf):
x = strcat(u, v) %remove trailing white-spaces in each input
x = [u, v] %plain concatenation
x = sprintf('%s%s', u, v) %same
  댓글 수: 1
V E
V E 2016년 6월 23일
Thank you very much, that was exactly it ;).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Signal Operations에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by