How to calculate the length of output that sprintf will generate?

后端 未结 7 1968
谎友^
谎友^ 2021-02-07 01:35

Goal: serialize data to JSON.

Issue: i cant know beforehand how many chars long the integer is.

i thought a good way to do this

相关标签:
7条回答
  • 2021-02-07 02:06

    Printf supports %n format parameter, which means "write position of %n in output string to int value pointed by x-parameter), so:

    int x;snprintf(NULL, 0, "Message: %s%n", "Error!",&x);
    

    Should works!

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