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

后端 未结 7 1989
谎友^
谎友^ 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:44

    Calling snprintf(nullptr, 0, ...) does return the size but it has performance penalty, because it will call IO_str_overflow and which is slow.

    If you do care about performance, you can pre-allocate a dummy buffer and pass its pointer and size to ::snprintf. it will be several times faster than the nullptr version.

    template
    size_t get_len(const char* format, Args ...args) {
      static char dummy[4096]; // you can change the default size
      return ::snprintf(dummy, 4096, format, args...) + 1; // +1 for \0
    }
    

提交回复
热议问题