Concatenating using the C++ "+" (plus) operator program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ operator+ to concatenate two string objects in C++ programming

To show: How to concatenate using "+" operator in C++ programming


// concatenating using "+" operator C++ program example

#include <string>

#include <iostream>

using namespace std;


int main(void)


// declaring an object of type basic_string<char>

string str1("StringOne");

string str2("StringTwo");

// declaring a C-style string

char *str3 = "StringThree";


// declaring a character constant

char chr = '?';

cout<<"str1 string is = "<<str1<<endl;

cout<<"str2 string is = "<<str2<<endl;

cout<<"str3 C-style string is = char *str3 = \"StringThree\" = "<<str3<<endl;

cout<<"A character constant chr is = "<<chr<<endl;


// concatenates an object of type basic_string with an object of type basic_string

cout<<"\nOperation: str12 = str1 + str2"<<endl;

string str12 = str1 + str2;

cout<<"str12 = "<<str12<<endl;


// concatenates an object of type basic_string with an object of C-style string type

cout<<"\nOperation: str13 = str1 + str3"<<endl;

string str13 = str1 + str3;

cout<<"str13 = "<<str13<<endl;


// concatenates an object of type basic_string with a character constant

cout<<"\nOperation: str13chr = str13 + chr"<<endl;

string str13chr = str13 + chr;

cout<<"str13chr = "<<str13chr<<endl;


return 0;



Output example:


str1 string is = StringOne

str2 string is = StringTwo

str3 C-style string is = char *str3 = "StringThree" = StringThree

A character constant chr is = ?


Operation: str12 = str1 + str2

str12 = StringOneStringTwo


Operation: str13 = str1 + str3

str13 = StringOneStringThree


Operation: str13chr = str13 + chr

str13chr = StringOneStringThree?

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index