我认为这将非常简单,但它提出了一些困难。如果我有
std::string name = "John";
int age = 21;
如何组合它们以获得单个字符串 "John21"
?
Boost::lexical_cast
、std::stringstream
、std::strstream
(已弃用)和 sprintf
与 snprintf
。
按字母顺序:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
是安全的,但很慢;需要 Boost(仅标题);大多数/所有平台都是安全的,需要 C++11(to_string() 已包含在 #include
在 C++11 中,您可以使用 std::to_string
,例如:
auto result = name + std::to_string( age );
如果您有 Boost,则可以使用 boost::lexical_cast<std::string>(age)
将整数转换为字符串。
另一种方法是使用字符串流:
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
。这不是标准功能,因此如果您使用它,您的代码将无法移植。有些编译器不支持它。
char buffer[128];缓冲区[sizeof(buffer)-1] = '\0'; snprintf(buffer, sizeof(buffer)-1, "%s%d", name.c_str(), age); std::cout << 缓冲区 << std::endl;
sprintf
,只有 snprintf
。
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.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 窃取。
s
是堆栈变量,调用 itos
后 s
的内存将是空闲的。 s
应该从堆中分配,而 free
应该在使用后分配,对吗?
这是最简单的方法:
string s = name + std::to_string(age);
如果您有 C++11,则可以使用 std::to_string
。
例子:
std::string name = "John";
int age = 21;
name += std::to_string(age);
std::cout << name;
输出:
John21
name += std::to_string(static_cast<long long>(age));
here
name += std::to_string(age + 0LL);
怎么样?
在我看来,最简单的答案是使用 sprintf
函数:
sprintf(outString,"%s%d",name,age);
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
#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;
Googled [并经过测试:p]
这个问题可以通过多种方式解决。我将以两种方式展示它:
使用 to_string(i) 将数字转换为字符串。使用字符串流。代码:#include
在 C++20 中,您将能够:
auto result = std::format("{}{}", name, age);
同时您可以使用 the {fmt} library,std::format
是基于:
auto result = fmt::format("{}{}", name, age);
免责声明:我是 {fmt} 库和 C++20 std::format
的作者。
fmt::format(variable,name,age)
fmt::runtime
中
store.push_back(fmt::arg("1", "pi"));
,这也会引发异常fmt::vformat("{1} = {2}",store)
SYSTEMTIME t;?
fmt::format("{}",t);
一起使用吗?请给我一个例子。感谢您!
如果您想使用 +
连接任何具有输出运算符的内容,您可以提供 operator+
的模板版本:
template <typename L, typename R> std::string operator+(L left, R right) {
std::ostringstream os;
os << left << right;
return os.str();
}
然后你可以用简单的方式编写你的连接:
std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);
std::cout << bar << std::endl;
输出:
the answer is 42
这不是最有效的方法,但除非您在循环中进行大量连接,否则您不需要最有效的方法。
std::string
,因此不会成为字符串不可转换为所需类型的表达式中的候选者。例如,此 operator+
不适合用于 int x = 5 + 7;
中的 +
。考虑到所有因素,如果没有非常令人信服的理由,我不会定义这样的运算符,但我的目标是提供与其他人不同的答案。
std::string
、std::string_view
和 const char *
)的模板就足够了。
如果您使用的是 MFC,则可以使用 CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
托管 C++ 也有一个 string formatter。
作为一个班轮:name += std::to_string(age);
std::ostringstream 是一个很好的方法,但有时这个额外的技巧可能会很方便地将格式转换为单行:
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
现在您可以像这样格式化字符串:
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
#define
而不是 template
?使用可变参数模板,甚至可以传入多个令牌。但我很犹豫是否使用它,因为 <<
操作数的输出上的 static_cast
返回到 std::ostringstream
有点不安全。这是一个约定,所有输出器都返回一个指向原始流对象的引用,但这在标准中没有得到保证。
由于一个与 Qt 相关的问题已被关闭,有利于这个问题,这里是如何使用 Qt 来做到这一点:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
字符串变量现在有 someIntVariable 的值代替 %1,最后有 someOtherIntVariable 的值。
有更多选项可用于将整数(或其他数字对象)与字符串连接起来。它是Boost.Format
#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.Spirit (v2) 的 Karma
#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;
}
Boost.Spirit Karma 声称是fastest option for integer to string转换之一。
std::ostringstream
#include
std::to_string (C++11)
std::string 查询(“约翰” + std::to_string(age));
boost::lexical_cast
#include
下面是如何使用 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
}
您可以使用下面给出的简单技巧将 int 连接到字符串,但请注意,这只适用于整数为单个数字的情况。否则,将整数逐位添加到该字符串。
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
我写了一个函数,它以 int 数字为参数,并将其转换为字符串文字。此函数依赖于将单个数字转换为其等效字符的另一个函数:
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;
}
在 C++ 20 中,您可以拥有一个可变参数 lambda,它可以在几行中将任意可流式类型连接到一个字符串:
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() 保证 ostringstream 对象的字符串缓冲区在下次调用 lambda 时为空。
不定期副业成功案例分享
String(number)
。