How to get formatted std :: string in C ++ without length restrictions

What is the best way (short using standard libraries and easy to understand) to do this in C ++:

std::string s = magic_command("%4.2f", 123.456f)
  • no length restrictions (char s [1000] = ...)
  • where "% 4.2f" is any c-format string (which will be issued, for example, printf)

I know snprintf malloc combo is offered for pure c in

writing formatted data of unknown length to a string (C programming)

but is there a better, less verbose way to do this using C ++?

I also know about the std :: ostringstream method suggested in

Convert float to std :: string in C ++

but I want to pass a format string c, such as "% 4.2f", and I could not find a way to do this with ostringstream.

0
5

, , , , , :

  • , , , 4 .
  • stringstream + setprecision, ,
  • , , snprintf/check overflow/dynamic allocation, "utils"
  • , (, ):
    • boost , Boost.Format
    • GNU/BSD , asprintf
0

Boost.Format:

std::string s = boost::str(boost::format("%4.2f") % 123.456f);

, Boost , .

+8

std::stringstream ( setprecision) .str(), std::string.

+5

++ , . magic_command , asprintf ( vasprintf ).

, *asprintf GNU/BSD. , Windows. , POD ( , ).

std::string magic_command(const std::string& format, ...)
{
    char* ptr;
    va_list args;
    va_start(args, format);
    vasprintf(&ptr, format.c_str(), args);
    va_end(args);

    std::unique_ptr<char, decltype(free)&> free_chars(ptr, free);
    return std::string(ptr);
}
+5

If you literally want to use your forgo syntax and security, I would write a small wrapper class that wraps snprintf. I would start using a local, automatic, small-sized buffer (say 2048?) And call it snprintfonce. If this succeeds, return std::stringcreated from this buffer. If you go, select the std::stringdesired size and repeat snprintf.

+1
source

Source: https://habr.com/ru/post/1622528/


All Articles