这里的代码来自boost自带的帮助文档,我只做了少量的修改,将其连接起来
lexical_1.cpp
#include <boost/lexical_cast.hpp>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
int main(int argc,char* argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<long> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<long>(*argv)); //字符串转化成long类型的数字
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
std::copy(args.begin(),args.end(),std::ostream_iterator<long>(std::cout,","));
std::cout << std::endl;
std::vector<std::string> args2;
args.clear();
for (int i = 0;i<10;i++)
{
args.push_back((long)i);
}
std::vector<long>::iterator pos;
for(pos = args.begin();pos != args.end();pos++)
{
try
{
args2.push_back(lexical_cast<std::string>(*pos)); //long类型的数字转化成字符串
}
catch(bad_lexical_cast &)
{
args2.push_back(" ");
}
}
std::copy(args2.begin(),args2.end(),std::ostream_iterator<std::string>(std::cout,","));
std::cout << std::endl;
system("pause");
}
lexical_1.cpp
#include <boost/lexical_cast.hpp>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
int main(int argc,char* argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<long> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<long>(*argv)); //字符串转化成long类型的数字
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
std::copy(args.begin(),args.end(),std::ostream_iterator<long>(std::cout,","));
std::cout << std::endl;
std::vector<std::string> args2;
args.clear();
for (int i = 0;i<10;i++)
{
args.push_back((long)i);
}
std::vector<long>::iterator pos;
for(pos = args.begin();pos != args.end();pos++)
{
try
{
args2.push_back(lexical_cast<std::string>(*pos)); //long类型的数字转化成字符串
}
catch(bad_lexical_cast &)
{
args2.push_back(" ");
}
}
std::copy(args2.begin(),args2.end(),std::ostream_iterator<std::string>(std::cout,","));
std::cout << std::endl;
system("pause");
}