我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
在我看来,最简单的答案是使用sprintf函数:
sprintf(outString,"%s%d",name,age);
其他回答
您可以使用下面给出的简单技巧将int连接到string,但请注意,这仅适用于integer为个位数时。否则,向该字符串逐位添加整数。
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
如果你有c++ 11,你可以使用std::to_string。
例子:
std::string name = "John";
int age = 21;
name += std::to_string(age);
std::cout << name;
输出:
John21
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
那么你的用法应该是这样的
std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;
谷歌[并测试:p]
作为一个与Qt相关的问题,下面是如何使用Qt:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
字符串变量现在有someIntVariable的值代替%1,someOtherIntVariable的值在结尾。
我写了一个函数,它以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;
}