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

前端 未结 23 2308
南方客
南方客 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: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;
    }
    

提交回复
热议问题