How to concatenate an STD:: string and an int?

Keywords: ascii

I think it's really simple, but there are some difficulties. If I had

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

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

#1 building

In C ++ 11, you can use STD:: to string, for example:

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

#2 building

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

#3 building

I wrote a function that takes an int number as an argument and converts it to string text. This function depends on another function that converts a 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;
}

#4 building

Common answers: itoa()

It's not good. itoa is nonstandard, such as Here .

#5 building

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

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

Posted by joquius on Mon, 30 Dec 2019 06:20:12 -0800