【问题标题】:boost::format form c-string or std::stringboost::format 形式 c-string 或 std::string
【发布时间】:2012-04-13 00:22:28
【问题描述】:

如何使用字符串或std::string 创建boost::format 类型格式化程序对象。
尝试使用以下无法运行的代码。想要实现与以下代码等效的代码(语义上):

    format fobj("first-> %1% , second-> %2%");
    std::stringstream s;
    s<<fobj %1 %"%1%.";    //so that I can use s.str() to create a boost object
// How to create fmt object  HERE  
    ss<< fmt %"replacedtext";
    cout<<s.str()<<endl;
    cout<<ss.str();

示例案例:
s 应为 "first-> 1 , second-> %1%。"
这样我就可以使用这个 s.str() 字符串来创建另一个格式对象 fmt,我可以将替换值提供给它。

大家有什么想法吗??

【问题讨论】:

    标签: c++ boost string-formatting stringstream stdstring


    【解决方案1】:

    我不清楚您要做什么,boost::format 文档是一个很好的起点,有许多清晰的示例展示了如何使用该类。

    您可以创建格式化程序对象并通过不同的操作输入元素(不像 printf,所有参数都需要满足您传入的 va_arg)。

    boost::format fmter("%2% %1%");
    fmter % 36; 
    fmter % 77;
    

    然后您可以从结果中获取一个字符串。

    std::string s  = fmter.str();
    

    注意有一个number of exceptions可以被抛出。

    如果您正在寻找可以动态创建格式字符串的东西,您可以通过多种方式来实现。

    std::string strFormatString = "first-> %1% second-> %2%";
    boost::format formatter( strFormatString.c_str() );
    formatter % value1;
    formatter % strFormatString.c_str();
    boost::format secondFormatter( formatter.str() );  // etc etc etc
    

    【讨论】:

    • 目标与你写的完全相反:) 你写的是 std::string s = fmter.str();从语义上说从格式化程序中获取字符串。我的意思是从字符串中获取格式化程序。该字符串可能来自格式化程序或其他东西
    • 感谢@Konrad。这正是我想要的。
    • 似乎 boost::format 示例在 boost.org/doc/libs/1_52_0/libs/format/example/… 的“ s= str( format(" %d %d ") % 11 % 22 )" 行中不起作用。 boost::format(...).str() 应该被调用。还是我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 2017-01-08
    • 2011-09-17
    • 2015-09-18
    • 2017-08-22
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多