필터 지우기
필터 지우기

Passing formatted string output of sprintf to fprintf

조회 수: 6 (최근 30일)
Louis
Louis 2020년 5월 11일
댓글: Louis 2020년 5월 13일
I have a writeToLog function which takes formatted string and uses fprintf to print the formated string to both a log file and to a command window.
When I use fprintf to print a file location by passing file directory directly, it works perfectly:
dir = '\\file_server\parent_dir\sub_dir';
fprintf('Saving the log file to: %s\n', dir))
However, when I pass the formated string output of sprintf to fprintf, it errors out:
format_str = sprintf('Saving the log file to: %s\n', dir)
>> fprintf(format_str)
Warning: Escaped character '\p' is not valid. See 'doc sprintf' for supported special characters.
Saving the log file to: \file_server>>
Is there a way for fprintf to print the formatted string as is?
  댓글 수: 2
Hank
Hank 2020년 5월 11일
Since the string is already formatted, just use
disp(formated_str)
Louis
Louis 2020년 5월 11일
Thanks for the suggestions.
I have a helper function
function writeToLog(fid, formatted_str)
% print to log file
fprintf(fid, formatted_str);
% print to command window
fprintf(formatted_str);
end
And the purpose of this function is to write information to both the command window and a log file.
Since I wanted to keep this function just take the file id and the formatted string, every where in my code I have
formatted_str = sprintf(...);
writeToLog(fid, formatted_str);
Not sure display alone will help me to write to both the command window and the log file.
Any suggestions?

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

채택된 답변

Image Analyst
Image Analyst 2020년 5월 11일
You'll need to do
function writeToLog(fid, formatted_str)
% Write to log file.
fprintf(fid, '%s\n', formatted_str);
% Print to command window.
fprintf('%s\n', formatted_str);
end

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 5월 11일
format_str = sprintf('Saving the log file to: %s\n', dir)
>> fprintf('%s', format_str)
You don't want to use the string created by sprintf as the format specifier, you want to use it as data with the '%s' format specifier.
BTW, you may want to use a different variable name to contain the name of your directory. dir already has a meaning in MATLAB.
  댓글 수: 3
Steven Lord
Steven Lord 2020년 5월 13일
If the second input to writeToLog has always passed through sprintf, it's always going to be text (either a char or string array.) So tell fprintf that just like Image Analyst suggested.
Louis
Louis 2020년 5월 13일
Thank you!

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by