Conversion of variables type int to type char*. C++ [duplicate]

this question already has answers here : Command for combination of integers. C++ (2 responses) Closed for 4 years.

I have the following method that takes two int variables as a parameter and I need to concatenate these two values into a char* variable, only for this to be possible it is necessary that these two INT variables be converted to type char*.

void exemplo(int amountVariables1, int amountVariables2){
   char *strPosition;
   //código para conversão de amountVariables1 e amountVariables2.
   strPosition = strcat(amountVariables1, amountVariables2);
}

How Should I perform type conversion so that it is possible to perform concatenation of these variables?

Author: Maniero, 2016-07-28

3 answers

Can do with sprintf :

#include <stdio.h>

void exemplo(int i1, int i2) {
    char s[16];
    sprintf(s, "%d%d", i1, i2);
    printf(s);
}

void main() {
    exemplo(12, 34);
}
 6
Author: Victor T., 2016-07-28 19:04:57

How about:

#include <stdio.h>

char * concatint( char * str, int a, int b )
{
    sprintf( str, "%d%d", a, b );
    return str;
}

int main ( void )
{
    char str[ 100 ] = {0};

    printf( "%s\n", concatint( str, 123, 456 ) );
    printf( "%s\n", concatint( str, 1, 2 ) );
    printf( "%s\n", concatint( str, 1000, 9999 ) );
    printf( "%s\n", concatint( str, 0, 0 ) );

    return 0;
}

/* fim-de-arquivo */

Output:

$ ./concatint 
123456
12
10009999
00
 5
Author: Lacobus, 2016-07-28 19:07:19

Follows another form (C++11):

#include <iostream>
#include <sstream>

using namespace std;

string concatInt(int num1, int num2){
    stringstream ss;
    ss << num1 << num2;

    return ss.str();
}

int main() {
    string strPosition = concatInt(1, 11);
    // Converte String para char*
    char* chrPosition = &strPosition[0]; 

    cout << chrPosition << endl;
    return 0;
}

See demonstração

 1
Author: stderr, 2016-07-28 21:10:40