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

后端 未结 7 1979
谎友^
谎友^ 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!

提交回复
热议问题