我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
有更多的选项可以用来连接整数(或其他数字对象)与字符串。它就是Boost。格式
#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;
int age = 22;
std::string str_age = str(format("age is %1%") % age);
}
还有Boost的Karma。精神(v2)
#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;
int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);
return 0;
}
提振。Spirit Karma声称是整数到字符串转换的最快选择之一。
其他回答
你可以像这样使用C函数itoa():
char buf[3];
itoa(age, buf, 10);
name += buf;
常见答案:itoa()
这很糟糕。正如这里指出的,Itoa是非标准的。
在c++ 20中,你可以做到:
auto result = std::format("{}{}", name, age);
与此同时,你可以使用{fmt}库,std::format基于:
auto result = fmt::format("{}{}", name, age);
声明:我是{fmt}库和c++ 20 std::格式的作者。
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
无耻地从http://www.research.att.com/~bs/bs_faq2.html窃取。