C++ Strings : Numbers and Strings

Numbers and Strings

Adding Numbers and Strings

C++ uses the “+” operator for both addition and concatenation.

* Numbers are added.
* Strings are concatenated.

Example
If you add two numbers, the result will be a number:

int x = 10;
int y = 20;
int z = x + y;

Note: z will be 30 (an integer)

//Numbers and Strings
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//	Note: Using "+"  operator two or more numeric values can be added.
	//	if we add two integers the result will also be an integer.
	
	int x = 10;
	int y = 20;
	int z = x + y; 
	cout<<"x "<<x<<" y "<<y<<" z "<<z<<endl;
	return(0);
}

Example:2
If you add two strings, the result will be a string concatenation:

string n1=”Hello”;
string n2=”World”;
string n3=n1+n2;
Note: // n3 will be HelloWorld (a string)

string x = “10”;
string y = “20”;
string z = x + y;

Note: // z will be 1020 (a string)

//Numbers and Strings
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//	Note: In C++ Using "+"  operator two or more strings can also be added.
	//	if we add two strings the result will also be a string.
	
	string n1="Hello";
	string n2="World";
	string n3=n1+n2;
	cout<<"n1 "<<n1<<" n2 "<<n2<<" n3 "<<n3<<endl;
	
	string a1 = "10";
	string a2 = "20";
	string a3 = a1 + a2;   
	cout<<"a1 "<<a1<<" a2 "<<a2<<" a3 "<<a3<<endl;
	
	return(0);
}

Example:3
If you try to add a number to a string, an error occurs:

string a1 = “Hello”;
int a2 = 10;
string a3 = a1 + a2; //error

//Numbers and Strings
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//	Note: If we try to add a string and an integer using "+"  operator 
	//  then an error will get generated

	string a1 = "Hello";
	int a2 = 10;
	string a3 = a1 + a2;  //error 
	cout<<"a1 "<<a1<<" a2 "<<a2<<" a3 "<<a3<<endl;
	
	return(0);
}

Example:4
Note: Error , a string cannot be added to an integer.

string x = “10”;
int y = 20;
string z = x + y;

//Numbers and Strings
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//	Note: If we try to add a string and an integer using "+"  operator 
	//  then an error will get generated

	string a1 = "10";
	int a2 = 20;
	string a3 = a1 + a2;  //error 
	cout<<"a1 "<<a1<<" a2 "<<a2<<" a3 "<<a3<<endl;
	
	return(0);
}