问题
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 ;
回答1:
You need to include
#include <string>
#include <iostream>
回答2:
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.
回答3:
There are several problems with your code:
WordList
is not defined anywhere. You should define it before you use it.- You can't just write code outside a function like this. You need to put it in a function.
- You need to
#include <string>
before you can use the string class and iostream before you usecout
orendl
. string
,cout
andendl
live in thestd
namespace, so you can not access them without prefixing them withstd::
unless you use theusing
directive to bring them into scope first.
回答4:
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;
}
回答5:
You do not have to reference std::cout
or std::endl
explicitly.
They are both included in the namespace std
. using namespace std
instead of using scope resolution operator ::
every time makes is easier and cleaner.
#include<iostream>
#include<string>
using namespace std;
回答6:
If you are using linux system then you need to add
using namespace std;
Below headers
If windows then make sure you put headers correctly
#include<iostream.h>
#include<string.h>
Refer this it work perfectly.
#include <iostream>
#include <string>
int main ()
{
std::string str="We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
std::string str2 = str.substr (3,5); // "think"
std::size_t pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos);
// get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
来源:https://stackoverflow.com/questions/6320995/why-i-cannot-cout-a-string