Conversion of variables type int to char*. C++

Asked

Viewed 1,174 times

2

I have the following method that takes two int variables as 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 are converted to char type*.

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 the type conversion so that it is possible to concatenate these variables?

  • 1

    Evandro, try to decide whether to do it in C or C++ and use the appropriate tag. (the Portuguese version of the site is still new and good, so no one complains much)

  • It seems to me that this matter is exactly the same of your other question (although now you have been clearer). If so, do not open multiple questions for the same question, okay? Instead, edit the original question to make it clearer.

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);
}

5

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 */

Exit:

$ ./concatint 
123456
12
10009999
00

1

Follow 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.