disp(fprintf())打印fprintf和字符数.为什么?
巧合的是,我发现disp(fprintf())
打印出fprintf的字符串及其所包含的字符数.我知道disp()
是多余的,但是出于纯粹的好奇心,我想知道为什么它打印字符数,因为这一天实际上可能会有所帮助.
例如
By coincidence I discovered, that disp(fprintf())
prints the string of fprintf plus the number of characters that it has. I know, that the disp()
is reduntant, but just out of pure curiosity I want to know, why it prints the number of characters, since this might be actually helpful one day.
For example
disp(fprintf('Hi %i all of you',2))
产生
大家好,大家15个
Hi 2 all of you 15
The reason for the specific behaviour mentioned in the question is the call to FILEprintf fprintf
with a storage variable:
nbytes = fprintf(___)
使用前面语法中的任何输入参数返回fprintf
写入的字节数.
nbytes = fprintf(___)
returns the number of bytes thatfprintf
writes, using any of the input arguments in the preceding syntaxes.
所以发生的情况是disp(fprintf(...))
首先按照fprintf
打印文本,但没有存储变量,但是disp
仅看到fprintf
的存储变量,它是字符串的字节数,因此输出.
So what happens is that disp(fprintf(...))
first prints the text as per fprintf
without a storage variable, but disp
sees only the storage variable of fprintf
, which is the number of bytes of your string, hence the output.
此外,如果要显示字符串,则需要STRINGprintf: sprintf
:
As an addition, if you want to display strings, you need STRINGprintf: sprintf
:
disp(sprintf('Hi %i all of you',2))
Hi 2 all of you
文档向我展示的是sprintf
仅用于字符串格式化,您可以将其用于将图形添加到文本,设置顺序文件名等,而fprintf
则可以写入文本文件.
What the docs show me is that sprintf
is exclusively used for string formatting, which you can use for adding text to a graph, setting up sequential file names etc, whilst fprintf
writes to a text file.
str = sprintf(formatSpec,A1,...,An)
按照列顺序按formatSpec
格式化数组A1
,...,An
中的数据,并将结果返回到字符串str
.
str = sprintf(formatSpec,A1,...,An)
formats the data in arraysA1
,...,An
according toformatSpec
in column order, and returns the results to stringstr
.
fprintf(fileID,formatSpec,A1,...,An)
按列顺序将formatSpec
应用于数组A1
,... An
的所有元素,并将数据写入文本文件. fprintf
使用对fopen
的调用中指定的编码方案.
fprintf(fileID,formatSpec,A1,...,An)
applies the formatSpec
to all elements of arrays A1
,...An
in column order, and writes the data to a text file. fprintf
uses the encoding scheme specified in the call to fopen
.
fprintf(formatSpec,A1,...,An)
格式化数据并在屏幕上显示结果.
fprintf(formatSpec,A1,...,An)
formats data and displays the results on the screen.
用于在屏幕上显示文本,因此disp(sprintf())
或fprintf
是相等的,但是如果要将结果存储在字符串中,则必须使用sprintf
,并且如果要将其写入文本文件,则必须使用fprintf
.
For displaying text on screen therefore disp(sprintf())
or fprintf
are equal, but if you want to store the results in a string you have to use sprintf
and if you want to write it to a text file you have to use fprintf
.