sprintf format specifiers won't print newline
이전 댓글 표시
I'm trying to create a string that has a newline in it. My problem is with sprintf. I'm trying to put a newline (\n) character in my string, and it's behaviour is very strange... sometimes sprintf returns an empty string, and sometimes it just prints '\n' as part of the text. I want it to actually insert a line.
This is sort of what my string looks like, but with some variables inserted between the angle brackets:
entry = '% * < >\n';
I tried going straight ahead with sprintf:
sprintf(entry)
This produces
Empty string: 1-by-0
I tried accounting for the newline:
sprintf('\n', entry)
This seems to produce just a newline. I then thought maybe the percent sign was special, so I tried the 'escape character' syntax which is mentioned on the sprintf reference page but not really explained:
sprintf('%%', entry)
This produces just a percent sign. Next I tried using the string specifier %s. I found that
sprintf('%s', entry)
produced
% * < >\n
and that
sprintf('%s\n', entry)
produced the same thing but with a newline after the string, but not where my actually '\n' is. Whenever I add '%%' in there, it just prints out a percent sign. Can anyone tell me what I'm doing wrong? This is puzzling because simply doing sprintf(string) works for me with other strings that have newlines in them.
채택된 답변
추가 답변 (2개)
Honglei Chen
2012년 8월 3일
% and \ are escape characters so you need to treat them special, try
sprintf('%%*<>\\n');
You can find this information in the doc
doc sprintf
or
help sprintf
댓글 수: 4
Frances
2012년 8월 3일
Honglei Chen
2012년 8월 3일
then
sprintf('%%*<>\n')
should work, what's the issue? You can insert it anywhere
sprintf('%%\n*<>')
Azzi Abdelmalek
2012년 8월 3일
the result is
%*<>
Honglei Chen
2012년 8월 3일
There is a new line if you look carefully
Image Analyst
2012년 8월 3일
편집: Image Analyst
2012년 8월 3일
It's just a regular sprintf() like you're used to with other languages:
outputString = sprintf('%s\n%d\n%f', myString, myInteger, myDouble);
Simply put in the specifier %s, %d, etc. for the variable you want to insert, then put in \n whenever you want your string to start on a new line. For example:
myString = 'Hello Frances';
myInteger = 42;
myDouble = pi;
outputString = sprintf('%s\n%d%%\n%f', myString, myInteger, myDouble)
In the command window you'll see:
outputString =
Hello Frances
42%
3.141593
Note, each is on a new line.
카테고리
도움말 센터 및 File Exchange에서 Board games에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!