How would you append an integer to a char*
in c++?
We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.
Each character has an ASCII code, so it's already a number in C. If you want to convert an integer to a character, simply add '0' .
First convert the int to a char*
using sprintf()
:
char integer_string[32]; int integer = 1234; sprintf(integer_string, "%d", integer);
Then to append it to your other char*, use strcat()
:
char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string strcat(other_string, integer_string); // other_string now contains "Integer: 1234"
You could also use stringstreams.
char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;
The string can then be accessed using ss.str();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With