sprintf before fprintf breaks newline
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Guillaume
on 23 Jun 2016
Edited: Guillaume
on 23 Jun 2016
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
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!