Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append an int to char*

How would you append an integer to a char* in c++?

like image 964
user37875 Avatar asked Dec 07 '08 02:12

user37875


People also ask

Can I add int to char?

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.

Can we add int to char in c?

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' .


2 Answers

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" 
like image 108
Paige Ruten Avatar answered Sep 21 '22 01:09

Paige Ruten


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

like image 35
Sydius Avatar answered Sep 17 '22 01:09

Sydius