Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ String Concatenation operator<<

Tags:

I have realised my mistake. I was trying to concatenate two strings.

I have just started to learn C++. I have a problem about string concatenation. I don't have problem when I use:

cout << "Your name is"<<name; 

But when I try to do it with a string:

string nametext; nametext = "Your name is" << name; cout << nametext; 

I got an error. How can I concatenate two strings?

like image 750
backspace Avatar asked Feb 03 '14 13:02

backspace


People also ask

Can you concatenate strings in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

How do I concatenate a char to a string in C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

Is concatenation operator in C?

There is no string concatenation operator in C.

How do you concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


2 Answers

For string concatenation in C++, you should use the + operator.

nametext = "Your name is" + name; 
like image 50
Creris Avatar answered Sep 19 '22 15:09

Creris


First of all it is unclear what type name has. If it has the type std::string then instead of

string nametext; nametext = "Your name is" << name; 

you should write

std::string nametext = "Your name is " + name; 

where operator + serves to concatenate strings.

If name is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write

std::string nametext( "Your name is " ); nametext.append( name ); 

or

std::string nametext( "Your name is " ); nametext += name; 
like image 25
Vlad from Moscow Avatar answered Sep 19 '22 15:09

Vlad from Moscow