フィルターのクリア

Odd behavior combining sprintf and fprintf?

4 ビュー (過去 30 日間)
Matthew Masarik
Matthew Masarik 2014 年 6 月 18 日
コメント済み: Les Beckham 2014 年 6 月 18 日
When I create a formatted string using sprintf and then print it to screen using fprintf, I am getting some odd behavior when the formatted string contains the '%' character. Example:
fprintf( sprintf( '%% \n' ) );
displays nothing on my screen. I can disp the formatted string and get the expected output, or print to screen directly by formatting the string with fprintf and get the expected output. I've tested this on OS X and Linux and I see the same behavior.
The problem is that I build a formatted string using sprintf and grab it's length to overwrite it later, and then I want to print to screen using fprintf, but when I do I lose my '%' characters. I'm not using disp because it doesn't appear to be printing exactly what's in the formatted string.
Any thoughts on what I'm doing wrong, or what I can do differently? Thanks for your help.

採用された回答

Roger Wohlwend
Roger Wohlwend 2014 年 6 月 18 日
Try
fprintf(sprintf('%%%%\n'))
In order to print a % with the fprintf command, you have give the function two %-characters:
fprintf('%%')
The same is true for the sprintf-command. So sprintf turns two %-characters into one, and as you need two for fprintf, your string has to contain four %-characters.
  2 件のコメント
Matthew Masarik
Matthew Masarik 2014 年 6 月 18 日
Thanks, that does fix the printing issue. The length of the string is then wrong, but I can account for the additional characters and fix it. Thanks again.
Les Beckham
Les Beckham 2014 年 6 月 18 日
Another approach is this:
fprintf('%s', sprintf('%%\n'))

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by