如何获得一个格式化的std :: string在c ++没有长度限制 [英] How to get a formatted std::string in c++ without length liminations

查看:367
本文介绍了如何获得一个格式化的std :: string在c ++没有长度限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中这是最好的方法(简短,使用标准库和易于理解):

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)




  • 没有长度限制(char s [1000] = ...)

  • 其中%4.2f是任何c格式字符串(例如printf) li>

    • without length limitations (char s[1000] = ...)
    • where "%4.2f" is any c format string (which would be given to printf for example)
    • 我注意到snprintf malloc组合在

      I am aware of the snprintf malloc combo suggested for pure c in

      a href =http://stackoverflow.com/questions/1854353/writing-formatted-data-of-unknown-length-to-a-string-c-programming>将未知长度的格式化数据写入字符串(C编程)

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

      但是有更好,更简洁的方法来使用c ++吗?

      but is there a better, less verbose, way to do this with c++?

      我也知道

      将浮点数转换为c ++中的std :: string

      但我想传递ac格式字符串作为%4.2f,我找不到一个办法这样做与ostringstream。

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

      推荐答案

      因为似乎没有真正标准的方式做我想要的,我会投票你所有,并接受我自己的总结行动方案:

      All answers given are good since there seems to be no really standard way of doing what I want, I'll vote you all up, and accept my own sum up course of action:


      • 如果字符串足够短,可以手动估计它的大小,做它,乘以你的估计4,并静态分配。

      • 如果你可以逃脱stringstream + setprecision,做它,因为它是标准的

      • 如果不是,你愿意写和包括基于snprintf /检查溢出/动态分配的短助手函数,做它,并把它进入您的项目utils文件

      • 总是考虑哪个依赖对您的项目限制较少(也许您已经在使用其中的一个):

        • 如果boost限制较少,请使用Boost.Format

        • 如果GNU / BSD扩展限制较少,请使用asprintf

        • if the string is short enough to estimate its size by hand, do it, multiply your estimative by 4, and allocate it statically.
        • if you can get away with stringstream + setprecision, do it since it is standard
        • if not, and you are willing to write and include a short helper function based on snprintf/check overflow/dynamic allocation, do it and put it into your project "utils" file
        • finnally consider which dependency is less restrictive for your project (maybe you are already using one of them):
          • if boost is less restrictive, use Boost.Format
          • if GNU/BSD extensions are less restrictive, use asprintf

          这篇关于如何获得一个格式化的std :: string在c ++没有长度限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆