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?
This question is related to
c++
string
string-concatenation
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;
You can combine strings using stream string like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string name = "Bill";
stringstream ss;
ss << "Your name is: " << name;
string info = ss.str();
cout << info << endl;
return 0;
}
nametext = "Your name is" + name;
I think this should do
nametext
is an std::string
but these do not have the stream insertion operator (<<
) like output streams do.
To concatenate strings you can use the append
member function (or its equivalent, +=
, which works in the exact same way) or the +
operator, which creates a new string as a result of concatenating the previous two.
Source: Stackoverflow.com