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?
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.
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.
There is no string concatenation operator in C.
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.
For string concatenation in C++, you should use the +
operator.
nametext = "Your name is" + name;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With