disp(fprintf()) prints the fprintf and the number of characters. Why?

亡梦爱人 提交于 2019-12-20 01:36:14

问题


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))

results in

Hi 2 all of you 15


回答1:


The reason for the specific behaviour mentioned in the question is the call to FILEprintf fprintf with a storage variable:

nbytes = fprintf(___) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.

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.

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

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) formats the data in arrays A1,...,An according to formatSpec in column order, and returns the results to string str.

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) formats data and displays the results on the screen.

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.




回答2:


In the doc on fprintf, you see that the output from fprintf is the number of bytes printed. So here, the fprintf is printing Hi 2 all of you and the disp is printing the 15 returned by fprintf.



来源:https://stackoverflow.com/questions/33519743/dispfprintf-prints-the-fprintf-and-the-number-of-characters-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!