我以为这很简单,但它却有些困难。如果我有
std::string name = "John";
int age = 21;
如何将它们合并为一个字符串"John21"
?
我以为这很简单,但它却有些困难。如果我有
std::string name = "John";
int age = 21;
如何将它们合并为一个字符串"John21"
?
这是一个使用IOStreams库中的解析和格式化组件将int附加到字符串的实现示例。
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(1) { }
~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
erasable_facet<std::num_put<char,
std::back_insert_iterator<std::string>>> facet;
std::ios str(nullptr);
facet.put(std::back_inserter(s), str,
str.fill(), static_cast<unsigned long>(n));
}
int main()
{
std::string str = "ID: ";
int id = 123;
append_int(str, id);
std::cout << str; // ID: 123
}
auto make_string=[os=std::ostringstream{}](auto&& ...p) mutable
{
(os << ... << std::forward<decltype(p)>(p) );
return std::move(os).str();
};
int main() {
std::cout << make_string("Hello world: ",4,2, " is ", 42.0);
}
看到 https://godbolt.org/z/dEe9h75eb
使用move(os).str()可以保证在下一次调用lambda时,ostringstream对象的stringbuffer为空。
我写了一个函数,它以整数作为参数,并将其转换为字符串字面量。这个函数依赖于另一个函数,该函数将单个数字转换为其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;
}
itoa()
: char buf[3];
itoa(age, buf, 10);
name += buf;
Boost::lexical_cast
,std::stringstream
,std::strstream
(已弃用)以及sprintf
与snprintf
的比较。 - Fred Larson