Specifying maximum printf field width for numbers (truncating if necessary)?

前端 未结 5 1563
Happy的楠姐
Happy的楠姐 2021-02-19 00:09

You can truncate strings with a printf field-width specifier:

printf(\"%.5s\", \"abcdefgh\");

> abcde

Unfortunately it does no

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 00:12

    You could use snprintf to truncate from the right

    char buf[10];
    static const int WIDTH_INCL_NULL = 3;
    
    snprintf(buf, WIDTH_INCL_NULL, "%d", 1234); // buf will contain 12
    

提交回复
热议问题