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

前端 未结 2 492
再見小時候
再見小時候 2021-01-19 06:33

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

相关标签:
2条回答
  • 2021-01-19 07:00

    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.

    0 讨论(0)
  • 2021-01-19 07:02

    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.

    0 讨论(0)
提交回复
热议问题