Why I cannot cout a string?

Why I cannot cout string like this:

string text ;
text = WordList[i].substr(0,20) ;
cout << "String is  : " << text << endl ;

When I do this, I get the following error:

Error 2 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\users\mollasadra\documents\visual studio 2008\projects\barnamec\barnamec\barnamec.cpp 67 barnamec**

It is amazing, that even this is not working:

string text ;
text = "hello"  ;
cout << "String is  : " << text << endl ;

You need to include

#include <string>
#include <iostream>

You need to reference the cout's namespace std somehow. For instance, insert

using std::cout;
using std::endl;

on top of your function definition, or the file.


There are several problems with your code:

  1. WordList is not defined anywhere. You should define it before you use it.
  2. You can't just write code outside a function like this. You need to put it in a function.
  3. You need to #include <string> before you can use the string class and iostream before you use cout or endl.
  4. string, cout and endl live in the std namespace, so you can not access them without prefixing them with std:: unless you use the using directive to bring them into scope first.

Above answers are good but If you do not want to add string include, you can use the following

ostream& operator<<(ostream& os, string& msg)
{
os<<msg.c_str();

return os;
}