【问题标题】:Not getting a new line when using fprintf使用 fprintf 时没有换行
【发布时间】:2019-05-16 13:00:25
【问题描述】:

我为pyhtagorean值写了一个小函数:

function c = pyth(a,b)
% Takes two inputs of same size and returns the pythagorean of the 2 inputs
if size(a) == size(b) % checks for same size
    c = sqrt(a.*a + b.*b);  % calculates the pythagorean value
else
    fprintf('Error: Input sizes are not equal'); % returns if sizes are not the same
end

它可以正常工作,但是在它返回后,“>>”与我的输出位于同一行,而不是输出下方的新行。这仅适用于fprintf。这里:

>> pyth([1 2;3 4],[5 6;7 8])
ans =
    5.0990    6.3246
    7.6158    8.9443
>>
>> pyth([1 2],[1 2;3 4])
Error: Input sizes are not equal>> 

我该如何解决这个问题?

【问题讨论】:

    标签: matlab console printf newline error-logging


    【解决方案1】:

    fprintf 通常用于写入文件(因此开头的 f)。写入(文本)文件时,确保与操作系统无关的换行符的方法是在字符串末尾添加\r\n(又名CRLF,或[char(10) char(13)])。似乎在打印到控制台时,这并不重要(即\n 也适用于在 Linux 上运行的 MATLAB)。

    几个提示:

    • 您可以改用dispdisplay,因为它们会为您添加换行符。
    • 如果要显示错误,为什么不使用error
    • 如果您使用 fprintf 打印错误,您可能希望以 fprintf(2, ... ) 开头,因为这会将文本打印到 stderr,使其变为错误颜色(通常为红色)。

    【讨论】:

      【解决方案2】:

      使用 \n 换行:

      fprintf('Error: Input sizes are not equal\n');
      

      【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2021-08-11
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      相关资源
      最近更新 更多