Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to add numbers and strings in C++

Onyejiaku Theophilus Chidalu

Overview

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.

Addition of numbers

When two number variables are added together, the resulting output is a number.

Code

#include <iostream>
using namespace std;
 
int main () {
  //creating number variables
  int x = 5;
  int y = 10;

  // addition of the number variables
  int z = x + y;

  cout << z; // this should give 5 + 10 = 15
  return 0;
}

String concatenation

When two string variables are added or joined, the resulting output is a string concatenation.

Code

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  // creating the strings
  string x = "5";
  string y = "10";

  // string concatenation
  string z = x + y;

  cout << z; // this should give 510
  return 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.

Code

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  // creating a string variable
  string x = "5";
 
  // creating a number variable
  int y = 10;

  //adding the string and number variables
  string z = x + y;

  cout << z; // this should give 510
  return 0;
}

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring