如何连接std :: string和int?

问题描述 投票:610回答:22

我认为这很简单,但它存在一些困难。如果我有

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

如何组合它们以获得单个字符串"John21"

c++ int concatenation stdstring
22个回答
1057
投票

按字母顺序排列:

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);
  1. 是安全的,但很慢;需要Boost(仅限标题);大多数/所有平台
  2. 是安全的,需要C ++ 11(to_string()已经包含#include <string>
  3. 安全,快速;需要FastFormat,必须编译;大多数/所有平台
  4. (同上)
  5. 安全,快速;需要the {fmt} library,可以编译或在仅头模式下使用;大多数/所有平台
  6. 安全,缓慢,冗长;需要#include <sstream>(来自标准C ++)
  7. 很脆弱(你必须提供足够大的缓冲区),快速,冗长; itoa()是非标准扩展,并不保证可用于所有平台
  8. 很脆弱(你必须提供足够大的缓冲区),快速,冗长;什么都不需要(是标准的C ++);所有平台
  9. 很脆弱(你必须提供足够大的缓冲区),probably the fastest-possible conversion,verbose;需要STLSoft(仅限标题);大多数/所有平台
  10. safe-ish(你不会在一个声明中使用多个int_to_string()调用),速度快;需要STLSoft(仅限标题);仅Windows
  11. 是安全的,但很慢;需要Poco C++;大多数/所有平台

11
投票
#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]


8
投票

这个问题可以通过多种方式完成。我将以两种方式展示它:

  1. 使用to_string(i)将数字转换为字符串。
  2. 使用字符串流。 码: #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; }

7
投票

如果你想使用+连接任何有输出操作符的东西,你可以提供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

这不是最有效的方法,但除非你在循环中进行大量连接,否则不需要最有效的方法。


5
投票

如果您使用的是MFC,则可以使用CString

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

托管C ++也有一个 string formatter


4
投票

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

4
投票

由于Qt相关的问题被关闭而支持这个问题,以下是使用Qt的方法:

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

字符串变量现在有someOne Variable的值代替%1,而smOtherIng变量的值最后。


3
投票

有更多选项可用于将整数(或其他数字对象)与字符串连接起来。这是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的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;
}

Boost.Spirit Karma声称是fastest option for integer to string转换之一。


3
投票

常见答案:itoa()

这是不好的。 itoa指出,here是非标准的。


2
投票

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

2
投票
  • std :: ostringstream
#include <sstream>

std::ostringstream s;
s << "John " << age;
std::string query(s.str());
  • std :: to_string(C ++ 11)
std::string query("John " + std::to_string(age));
  • 提高:: lexical_cast的
#include <boost/lexical_cast.hpp>

std::string query("John " + boost::lexical_cast<std::string>(age));

250
投票

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

auto result = name + std::to_string( age );

2
投票

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

2
投票

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

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

Output:  John5

1
投票

随着{fmt} library

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

该库的一个子集被提议用于标准化为P0645 Text Formatting,如果被接受,上述内容将变为:

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

免责声明:我是{fmt}库的作者。


82
投票

如果你有Boost,你可以使用boost::lexical_cast<std::string>(age)将整数转换为字符串。

另一种方法是使用stringstreams:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

第三种方法是使用C库中的sprintfsnprintf

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

其他海报建议使用itoa。这不是标准功能,因此如果您使用它,您的代码将无法移植。有些编译器不支持它。


75
投票
#include <iostream>
#include <sstream>

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

50
投票
#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无耻地偷走了。


29
投票

这是最简单的方法:

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

22
投票

如果你有C ++ 11,你可以使用std::to_string

例:

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

name += std::to_string(age);

std::cout << name;

输出:

John21

18
投票

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

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

15
投票
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}
© www.soinside.com 2019 - 2024. All rights reserved.