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

前端 未结 23 2316
南方客
南方客 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:38

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

    Common Answer: itoa()

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

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

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

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

    0 讨论(0)
  • 2020-11-22 03:43
    #include <iostream>
    #include <sstream>
    
    std::ostringstream o;
    o << name << age;
    std::cout << o.str();
    
    0 讨论(0)
提交回复
热议问题