我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
std:: ostringstream
<sstream>#include std::ostringstream s; 与<<“约翰”<<年龄; std::string query(s.str());
std:: to_string (C + + 11)
std::string查询("John " + std::to_string(年龄));
boost:: lexical_cast
# include <刺激/ lexical_cast.hpp > std::string查询("John " + boost::lexical_cast<std::string>(age));
其他回答
std:: ostringstream
<sstream>#include std::ostringstream s; 与<<“约翰”<<年龄; std::string query(s.str());
std:: to_string (C + + 11)
std::string查询("John " + std::to_string(年龄));
boost:: lexical_cast
# include <刺激/ lexical_cast.hpp > std::string查询("John " + boost::lexical_cast<std::string>(age));
如果有Boost,可以使用Boost::lexical_cast<std::string>(age)将整数转换为字符串。
另一种方法是使用stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
第三种方法是使用C库中的sprintf或snprintf。
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
其他海报建议使用itoa。这不是一个标准函数,所以如果你使用它,你的代码将不能移植。有些编译器不支持它。
有更多的选项可以用来连接整数(或其他数字对象)与字符串。它就是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声称是整数到字符串转换的最快选择之一。
这是最简单的方法:
string s = name + std::to_string(age);
我写了一个函数,它以int数作为参数,并将其转换为字符串字面量。此函数依赖于另一个函数,该函数将单个数字转换为其char等价:
char intToChar(int num)
{
if (num < 10 && num >= 0)
{
return num + 48;
//48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
}
else
{
return '*';
}
}
string intToString(int num)
{
int digits = 0, process, single;
string numString;
process = num;
// The following process the number of digits in num
while (process != 0)
{
single = process % 10; // 'single' now holds the rightmost portion of the int
process = (process - single)/10;
// Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
// The above combination eliminates the rightmost portion of the int
digits ++;
}
process = num;
// Fill the numString with '*' times digits
for (int i = 0; i < digits; i++)
{
numString += '*';
}
for (int i = digits-1; i >= 0; i--)
{
single = process % 10;
numString[i] = intToChar ( single);
process = (process - single) / 10;
}
return numString;
}