A string in C++ is used to store text. A string
variable is one that contains a collection of characters that are enclosed with double quotes " "
.
In C++, we can use the +
operator for concatenation and addition.
It is worthy to note that the term string concatenation is used when
string
variables are joined together or concatenated. Whereas addition is used for when numbers are added.
When two number
variables are added together, the resulting output is a number.
#include <iostream>using namespace std;int main () {//creating number variablesint x = 5;int y = 10;// addition of the number variablesint z = x + y;cout << z; // this should give 5 + 10 = 15return 0;}
When two string
variables are added or joined, the resulting output is a string concatenation.
#include <iostream>#include <string>using namespace std;int main () {// creating the stringsstring x = "5";string y = "10";// string concatenationstring z = x + y;cout << z; // this should give 510return 0;}
Notice that from the code above, the concatenation of two strings is simply the joining of the strings. 5
as a string joined to another string 10
will give 510
.
Trying to join or add a string to a number will result in an error.
#include <iostream>#include <string>using namespace std;int main () {// creating a string variablestring x = "5";// creating a number variableint y = 10;//adding the string and number variablesstring z = x + y;cout << z; // this should give 510return 0;}