如何连接 std::string 和 int

发布于 2024-07-06 07:57:42 字数 146 浏览 9 评论 0原文

我认为这非常简单,但它带来了一些困难。 如果我有

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

如何将它们组合起来以获得单个字符串“John21”

I thought this would be really simple, but it's presenting some difficulties. If I have

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

How do I combine them to get a single string "John21"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

故人如初 2024-07-13 07:57:42

按字母顺序排列:

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 中)
  3. 是安全且快速的; 需要 FastFormat,必须对其进行编译; 大多数/所有平台
  4. 同上
  5. 都是安全且快速的; 需要{fmt}库,它可以在仅标头模式下编译或使用; 大多数/所有平台
  6. 安全、缓慢且冗长; 需要 #include (来自标准 C++)
  7. 很脆弱(必须提供足够大的缓冲区)、快速且冗长; itoa() 是一个非标准扩展,不能保证适用于所有平台,
  8. 它很脆弱(您必须提供足够大的缓冲区)、快速且冗长; 不需要任何东西(是标准 C++); 所有平台
  9. 都很脆弱(您必须提供足够大的缓冲区),可能是最快的转换,冗长; 需要 STLSoft (仅标题); 大多数/所有平台
  10. 都是安全的(您不使用多个 int_to_string() 在单个语句中调用),速度快; 需要 STLSoft (仅标题); 仅 Windows
  11. 安全,但速度慢; 需要 Poco C++ ; 大多数/所有平台

In alphabetical order:

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. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. (ditto)
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. 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
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms
动次打次papapa 2024-07-13 07:57:42

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

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

In C++11, you can use std::to_string, e.g.:

auto result = name + std::to_string( age );
思慕 2024-07-13 07:57:42

如果您有 Boost,则可以使用 boost::lexical_cast(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。 这不是标准函数,因此如果您使用它,您的代码将不可移植。 有些编译器不支持它。

If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).

Another way is to use stringstreams:

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

A third approach would be to use sprintf or snprintf from the C library.

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

Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

不及他 2024-07-13 07:57:42
#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();
#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();
不忘初心 2024-07-13 07:57:42
#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 <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.

﹎☆浅夏丿初晴 2024-07-13 07:57:42

这是最简单的方法:

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

This is the easiest way:

string s = name + std::to_string(age);
自在安然 2024-07-13 07:57:42

如果您使用 C++11,则可以使用 std::to_string

示例:

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

name += std::to_string(age);

std::cout << name;

输出:

John21

If you have C++11, you can use std::to_string.

Example:

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

name += std::to_string(age);

std::cout << name;

Output:

John21
辞取 2024-07-13 07:57:42

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

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

It seems to me that the simplest answer is to use the sprintf function:

sprintf(outString,"%s%d",name,age);
白色秋天 2024-07-13 07:57:42
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}
漆黑的白昼 2024-07-13 07:57:42
#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]

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

Then your usage would look something like this

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [and tested :p ]

烟燃烟灭 2024-07-13 07:57:42

您可以使用 C++20 std::formatgodbolt):

std::string name = "John";
int age = 21;
std::string result = std::format("{}{}", name, age);

如果std::format 不可用,您可以使用{fmt} 库,它基于:

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

免责声明:我是 {fmt} 库和 C++20 std::format 的作者。

You can do it with C++20 std::format (godbolt):

std::string name = "John";
int age = 21;
std::string result = std::format("{}{}", name, age);

If std::format is not available you can use the {fmt} library, it is based on:

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

Disclaimer: I'm the author of the {fmt} library and C++20 std::format.

允世 2024-07-13 07:57:42

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

  1. 使用to_string(i)将数字转换为字符串。

  2. 使用字符串流。

    代码:

    <前><代码>#include <字符串>
    #include <流>
    #include;
    #include;
    使用命名空间 std;

    int main() {
    字符串名称=“约翰”;
    整数年龄=21;

    字符串答案1 =“”;
    // 方法 1). 字符串 s1 = to_string(年龄)。

    字符串 s1=to_string(年龄); // 知道整数被转换成字符串
    // 正如我们所知,在 C++ 中可以使用“+”轻松完成串联

    答案1=姓名+s1;

    计算<< 答案1 << 结束;

    // 方法 2). 使用字符串流

    ostringstream s2;

    s2 << 年龄;

    字符串 s3 = s2.str(); // str() 函数将数字转换为字符串

    字符串答案2 =“”; // 用于字符串连接。

    答案2=姓名+s3;

    计算<< 答案2 << 结束;

    返回0;
    }

This problem can be done in many ways. I will show it in two ways:

  1. Convert the number to string using to_string(i).

  2. 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;
    }
    
妳是的陽光 2024-07-13 07:57:42

作为一个衬垫:name += std::to_string(age);

As a one liner: name += std::to_string(age);

战皆罪 2024-07-13 07:57:42

如果您想使用 + 来连接任何具有输出运算符的内容,您可以提供 operator+ 的模板版本:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

然后您可以直接编写连接way:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

输出:

the answer is 42

这不是最有效的方法,但是除非您在循环内进行大量串联,否则您不需要最有效的方法。

If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

Then you can write your concatenations in a straightforward way:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

Output:

the answer is 42

This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.

烂柯人 2024-07-13 07:57:42

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

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

Managed C++也有一个
字符串格式化程序

If you are using MFC, you can use a CString

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

Managed C++ also has a
string formatter.

请止步禁区 2024-07-13 07:57:42

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

The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:

#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
    static_cast<std::ostringstream&>(          \
        std::ostringstream().flush() << tokens \
    ).str()                                    \
    /**/

Now you can format strings like this:

int main() {
    int i = 123;
    std::string message = MAKE_STRING("i = " << i);
    std::cout << message << std::endl; // prints: "i = 123"
}
╰◇生如夏花灿烂 2024-07-13 07:57:42

由于与 Qt 相关的问题已被关闭,因此有利于此问题,因此使用 Qt 执行此操作的方法如下:

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

字符串变量现在用 someIntVariable 的值代替 %1,并在末尾用 someOtherIntVariable 的值。

As a Qt-related question was closed in favour of this one, here's how to do it using Qt:

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

The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.

七分※倦醒 2024-07-13 07:57:42

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

#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 声称是 整数到字符串转换的最快选项

There are more options possible to use to concatenate integer (or other numerric object) with string. It is 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);
}

and Karma from Boost.Spirit (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 claims to be one of the fastest option for integer to string conversion.

怀中猫帐中妖 2024-07-13 07:57:42
  • std::ostringstream
#include ; 

  std::ostringstream s; 
  s <<   “约翰”<<   年龄; 
  std::string 查询(s.str()); 
  
  • std::to_string (C++11)
std::string query("John " + std::to_string(age)); 
  
  • 升压::词法转换
#include ; 

  std::string 查询("John " + boost::lexical_cast(age)); 
  
  • 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));
  • boost::lexical_cast
#include <boost/lexical_cast.hpp>

std::string query("John " + boost::lexical_cast<std::string>(age));
一影成城 2024-07-13 07:57:42

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

Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.

#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
}
执笏见 2024-07-13 07:57:42

常见答案: itoa()

这很糟糕。 itoa 是非标准的,正如这里指出的< /a>.

Common Answer: itoa()

This is bad. itoa is non-standard, as pointed out here.

茶色山野 2024-07-13 07:57:42

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

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

Output:  John5

You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.

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

Output:  John5
Saygoodbye 2024-07-13 07:57:42

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

There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:

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;
}
著墨染雨君画夕 2024-07-13 07:57:42

在 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 对象的字符串缓冲区为空。

In C++ 20 you can have a variadic lambda that does concatenate arbitrary streamable types to a string in a few lines:

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

see https://godbolt.org/z/dEe9h75eb

using move(os).str() guarantees that the ostringstream object's stringbuffer is empty next time the lambda is called.

枫以 2024-07-13 07:57:42

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

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

You can use the C function itoa() like this:

    char buf[3];
    itoa(age, buf, 10);
    name += buf;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文