Why won't \n give me a new line?
3 views (last 30 days)
Show older comments
I tried as below, and I expected it will give me:
//+
Point(10) = {0.77258 0.54961 0.56139 0.67184};
However, it gives me:
//+\nPoint(10) = {0.77258 0.54961 0.56139 0.67184};
And the code I wrote is:
for i_file = 1:10
point = rand(1,4);
fid = fopen('structure_test','wt');
fprintf(fid,'%s\n%s',['//+\nPoint(',num2str(i_file),') = {',num2str(point),'};']);
fid = fclose(fid);
end
0 Comments
Accepted Answer
Stephen23
on 22 Sep 2018
Edited: Stephen23
on 22 Sep 2018
Because all characters in the input strings are interpreted literally.
With fprintf and sprintf only the format strings can contain special characters (e.g. '\n') that will be interpreted in some special way. For the all of the other input arguments, all characters are literal.
fprintf('%s\n','\n')
special ^^ ^^ literal
Note that in MATLAB all char vectors are literal, so defining this:
vec = 'abc\ndef'
does not define a string with a newline (like in Python), it simply defines the char vector 'abc\ndef'. It is only inside the format string of sprintf and fprintf (and some other functions) where you can use special characters and expect them to be interpreted. Read the function help to know which functions support this.
1 Comment
Walter Roberson
on 22 Sep 2018
Small exception: inside a character vector, you need to use two ' in a row to represent one ' character.
'It''s a nuisance!'
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!