boost库之format

来源:互联网 发布:三元牛奶怎么样知乎 编辑:程序博客网 时间:2024/05/17 09:03

std::string是个好东西,但是估计用过的人都有体会,就是没有像CString的format函数,当然,可以用CString来做一个中转,比如:

CString strTmp = "";

strTmp.Format("%s%d", ***);

std::string str = strTmp;

 

不过由于MFC与平台有关,不能移植到非Windows平台下。借助boost库中的format,我们可以很方便的达到这个目的,且是平台无关的。除了格式看起来怪怪的,其他都还好,不过适应就好了。下面看代码。

 

 

#include <boost/format.hpp>
#include <string>
#include <iostream>

using boost::format;


int _tmain(int argc, _TCHAR* argv[])
{
 std::string str = "";
 std::string strName = "";

 

 std::cout<<"enter your name"<<std::endl;
 std::cin>>strName;

 str = boost::str(boost::format("%1%%2%") %"my name is :" %strName);

 std::cout<<str<<std::endl;                                          // if input stan , output: my name is stan


 str = boost::str(format("%1%  %2%") % 11 % 22);    // 11 22

 

 std::cout<<boost::format("%1% %2%") % "hello" % "world" <<std::endl;  //hello, world

 

 system("pause");
 return 0;
}