292 |
292 |
293 return 0; |
293 return 0; |
294 } |
294 } |
295 ``` |
295 ``` |
296 |
296 |
297 |
297 ### Automatic allocation for formatted strings |
|
298 |
|
299 The UCX utility function `ucx_asprintf()` and it's convenient shortcut |
|
300 `ucx_sprintf` allow easy formatting of strings, without ever having to worry |
|
301 about the required space. |
|
302 ```C |
|
303 sstr_t mystring = ucx_sprintf("The answer is: %d!", 42); |
|
304 ``` |
|
305 Still, you have to pass `mystring.ptr` to `free()` (or the free function of |
|
306 your allocator, if you use `ucx_asprintf`). |
|
307 If you don't have all the information ready to build your string, you can even |
|
308 use a [UcxBuffer](#buffer) as a target with the utility function |
|
309 `ucx_bprintf()`. |
|
310 ```C |
|
311 UcxBuffer* strbuffer = ucx_buffer_new(NULL, 512, UCX_BUFFER_AUTOEXTEND); |
|
312 |
|
313 for (unsigned int i = 2 ; i < 100 ; i++) { |
|
314 ucx_bprintf(strbuffer, "Integer %d is %s\n", |
|
315 i, prime(i) ? "prime" : "not prime"); |
|
316 } |
|
317 |
|
318 // print the result to stdout |
|
319 printf("%s", (char*)strbuffer->space); |
|
320 |
|
321 ucx_buffer_free(strbuffer); |
|
322 ``` |