我原以为这很简单,但它出现了一些困难。如果我有

std::string name = "John";
int age = 21;

我如何结合他们得到一个单一的字符串“John21”?


当前回答

作为一个与Qt相关的问题,下面是如何使用Qt:

QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);

字符串变量现在有someIntVariable的值代替%1,someOtherIntVariable的值在结尾。

其他回答

在我看来,最简单的答案是使用sprintf函数:

sprintf(outString,"%s%d",name,age);

下面是如何使用IOStreams库中的解析和格式化aspect将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
}

在c++ 20中,你可以做到:

auto result = std::format("{}{}", name, age);

与此同时,你可以使用{fmt}库,std::format基于:

auto result = fmt::format("{}{}", name, age);

声明:我是{fmt}库和c++ 20 std::格式的作者。

按字母顺序排列:

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);

is safe, but slow; requires Boost (header-only); most/all platforms is safe, requires C++11 (to_string() is already included in #include <string>) is safe, and fast; requires FastFormat, which must be compiled; most/all platforms (ditto) is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms safe, slow, and verbose; requires #include <sstream> (from standard C++) is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only is safe, but slow; requires Poco C++ ; most/all platforms

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"
}