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

2

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

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

How do I perform type conversion so that I can concatenate these variables?

    
asked by anonymous 28.07.2016 / 20:54

3 answers

6

You 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);
}
    
28.07.2016 / 21:04
5

What 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
    
28.07.2016 / 21:07
1

Here's another way (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;
}

View demonstração

    
28.07.2016 / 22:56