Can I do a concatenation of 2 chars? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis

Can I do a concatenation of 2 chars?

Like this: 'a'+'b'="ab"

2nd May 2017, 3:36 PM
Awantura Bator
Awantura Bator - avatar
3 Respostas
+ 8
you can with strings don't forget to add #include <string> string x; x="a"; x+="b"; and treat all chars as strings (use double quote marks "a") notice the following cout << "a" + "b"; results in error whilst string x = "a"; cout << x + "b" + "c"; is valid the reason for that is since you can concatanate into a string (second case) but cannot concatanate const characters (first case) whom ever wish to elaborate on this please do
2nd May 2017, 3:44 PM
Burey - avatar
+ 2
Just to add to the previous answer, if you have already declared char's and aren't adding string literals like Burey said (string literals are the quotes, like "a"), you can use a string library function: char a = 'a'; char b = 'b'; string str = ""; //declared empty string str.append(1, a); str.append(1, b); cout << str << endl; //outputs "ab" When you use append with a character, the first number you pass into the function is the number of copies of the character you want to append onto the string. For example, str.append(4, a) would result in str = "aaaa"; You can also use it with character literals as well: str.append(2, 'g'); // str = "gg";
2nd May 2017, 9:35 PM
Zeke Williams
Zeke Williams - avatar
Great, thanks! So that's why when I do something like this: char a='3'; cout << a-'0'; The output will be an int (it will subtract the ASCII codes of chars 3 and 0)?
2nd May 2017, 6:51 PM
Awantura Bator
Awantura Bator - avatar