How to concatenate a std::string and an int?

前端 未结 23 2315
南方客
南方客 2020-11-22 02:40

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

相关标签:
23条回答
  • 2020-11-22 03:30

    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
    
    0 讨论(0)
  • 2020-11-22 03:33

    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.

    0 讨论(0)
  • 2020-11-22 03:33

    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.

    0 讨论(0)
  • 2020-11-22 03:35
    #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 ]

    0 讨论(0)
  • 2020-11-22 03:36

    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"
    }
    
    0 讨论(0)
  • 2020-11-22 03:38

    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
    0 讨论(0)
提交回复
热议问题