My requirement is to join two characters. For example
int main()
{
char c1 ='0';
char c2 ='4';
char c3 = c1+c2;
cout<< c3;
}
The value which I am expecting is 04. But what I am getting is d
.
I know that char is single byte. My requirement is that in the single Byte of C3 is possible to merge/join/concat the c1,c2 and store the value as 04
Write a C program to join two strings.. We first take two string as input from user using gets function and store it in two character array. Now, we have to append first string at the end of second string. We can either use strcat function of string.h header file to concatenate strings or write our own function to append strings using pointers.
As you know, the best way to concatenate two strings in C programming is by using the strcat () function. However, in this example, we will concatenate two strings manually. Here, two strings s1 and s2 and concatenated and the result is stored in s1.
We are combining the two strings into one string. 2) Read the entered two strings using gets () function as gets (s1) and gets (s2). 3) Get the length of the string s1 using string library function strlen (s1) and initialize to j.
Method 1: Using strcat () function. The strcat () function is defined in “string.h” header file. The init and add string should be of character array (char*). This function concatenates the added string to the end of the init string. Method 2: Using append () function. string& string::append (const string& str) str: the string to be appended.
A char
is not a string
. So you can first convert the first char to a string and than add the next ones like:
int main()
{
char c1 ='0';
char c2 ='4';
auto c3 = std::string(1,c1)+c2;
std::cout<< c3;
}
What is "magic" std::string(1,c1)
:
It uses the std::string constructor of the form: std::string::string (size_t n, char c);
. So it "fills" the string with one single character of your given c1 which is the 0
.
If you add chars you get the result of adding the numeric value of it which is:
int main() {
std::cout << (int)c1 << std::endl;
std::cout << (int)c2 << std::endl;
std::cout << (int)c1+c2 << std::endl;
std::cout << char(c1+c2) << std::endl;
}
The numeric value as int from 0
is 48, from 4
it is 52. Add both you get 100. And 100 is a d
in ascii coding.
What you want is called a string of characters. There are many ways to create that in C++. One way you can do it is by using the std::string
class from the Standard Library:
char c1 = '0';
char c2 = '4';
std::string s; // an empty string
s += c1; // append the first character
s += c2; // append the second character
cout << s; // print all the characters out
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