如何在没有长度限制的情况下在c ++中获取格式化的std :: string

Cir*_*四事件 0 c++ string string-formatting

在c ++中执行此操作的最佳方法是什么(简言之,使用标准库并且易于理解):

std::string s = magic_command("%4.2f", 123.456f)
Run Code Online (Sandbox Code Playgroud)
  • 没有长度限制(char s [1000] = ...)
  • 其中"%4.2f"是任何c格式的字符串(例如,它将被赋予printf)

我知道为纯c建议的snprintf malloc组合

将未知长度的格式化数据写入字符串(C编程)

但使用c ++有没有更好,更简洁的方法呢?

我也知道建议的std :: ostringstream方法

在C++中将float转换为std :: string

但我想传递ac格式字符串,如"%4.2f",我找不到用ostringstream这样做的方法.

小智 8

你可以尝试Boost.Format:

std::string s = boost::str(boost::format("%4.2f") % 123.456f);
Run Code Online (Sandbox Code Playgroud)

它没有包含在标准中,但Boost与非标准库一样标准.


Luc*_*ore 5

我会使用std::stringstream(与之组合setprecision)代替,然后使用它.str()来获得std::string.


zne*_*eak 5

C++完全放弃了格式字符串的概念,因此没有标准的方法来实现它.但是,您可以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);
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

906 次

最近记录:

12 年,2 月 前