Adding Numbers and Strings
C++ uses the
+
operator for both addition and concatenation.Numbers are added. Strings are concatenated.
If you add two numbers, the result will be a number:
Example:
#include <iostream>
using namespace std;
int main () {
int x = 20;
int y = 21;
int z = x + y;
cout << z;
return 0;
}
//Output---> z will be 41 (an integer)
If you add two strings, the result will be a string concatenation:
Example:
#include <iostream>
#include <string>
using namespace std;
int main () {
string x = "20";
string y = "21";
string z = x + y;
cout << z;
return 0;
}
//Output---> z will be 2021 (a string)
If you try to add a number to a string, an error occurs:
Example:
string x = "20";
int y = 21;
string z = x + y; //Error
In next chapter will be study about String Length. ———————————————————————————————————————————————>