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

后端 未结 7 1974
谎友^
谎友^ 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 01:51

    To just obtain the length you can write:

    int length = snprintf(NULL, 0, "{data:%d}", 12312);
    

    Note that the return type is int. It may return -1 in case of some sort of error. Make sure your input data doesn't include long strings that might cause the total length to exceed INT_MAX !

提交回复
热议问题