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

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

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


常见答案:itoa()

这很糟糕。正如这里指出的,Itoa是非标准的。


#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窃取。


#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();

如果有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。这不是一个标准函数,所以如果你使用它,你的代码将不能移植。有些编译器不支持它。


#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}

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

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

如果你使用MFC,你可以使用CString

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);

托管c++也有一个 字符串格式化程序。


#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]


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

按字母顺序排列:

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


有更多的选项可以用来连接整数(或其他数字对象)与字符串。它就是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声称是整数到字符串转换的最快选择之一。


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

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

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


如果你想使用+来连接任何有输出操作符的东西,你可以提供一个操作符+的模板版本:

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

这不是最有效的方法,但你不需要最有效的方法,除非你在一个循环中做很多连接。


在c++ 11中,你可以使用std::to_string,例如:

auto result = 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

我写了一个函数,它以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;
}

下面是如何使用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
}

这是最简单的方法:

string s = name + std::to_string(age);

您可以使用下面给出的简单技巧将int连接到string,但请注意,这仅适用于integer为个位数时。否则,向该字符串逐位添加整数。

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

Output:  John5

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

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

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

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

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


这个问题可以用许多方法解决。我将以两种方式展示它:

Convert the number to string using to_string(i). Using string streams. Code: #include <string> #include <sstream> #include <bits/stdc++.h> #include <iostream> using namespace std; int main() { string name = "John"; int age = 21; string answer1 = ""; // Method 1). string s1 = to_string(age). string s1=to_string(age); // Know the integer get converted into string // where as we know that concatenation can easily be done using '+' in C++ answer1 = name + s1; cout << answer1 << endl; // Method 2). Using string streams ostringstream s2; s2 << age; string s3 = s2.str(); // The str() function will convert a number into a string string answer2 = ""; // For concatenation of strings. answer2 = name + s3; cout << answer2 << endl; return 0; }


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


作为一行:name += std::to_string(年龄);


在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()可以保证下次调用lambda时ostringstream对象的stringbuffer为空。


你可以像这样使用C函数itoa():

    char buf[3];
    itoa(age, buf, 10);
    name += buf;