为什么我不能找到一根绳子?

为什么我不能像这样 cout string:

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

执行此操作时,会得到以下错误:

错误2错误 C2679: 二进制’< <’: 没有找到操作符,该操作符采用类型为‘ std: : string’的右边操作数(或者没有可接受的转换) c: users mollasadra document Visual Studio 2008 project barnamec barnamec barnamec.cpp 67 barnamec * *

令人惊讶的是,即使这样也不管用:

string text ;
text = "hello"  ;
cout << "String is  : " << text << endl ;
254620 次浏览

你需要包括

#include <string>
#include <iostream>

您需要以某种方式引用 cout 的名称空间 std

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

在函数定义或文件的顶部。

您的代码有几个问题:

  1. WordList在任何地方都没有定义。您应该在使用它之前定义它。
  2. 你不能像这样在函数之外编写代码,你需要把它放在函数中。
  3. 在使用字符串类和 iostream 之前,需要先使用 #include <string>
  4. stringcoutendl位于 std名称空间中,因此如果不使用 std::作为前缀,就无法访问它们,除非您使用 using指令首先将它们放入作用域。

您不必显式引用 std::coutstd::endl
它们都包括在 namespace std中。using namespace std代替使用范围解析操作符 ::,每次使用都更简单、更清晰。

#include<iostream>
#include<string>
using namespace std;

如果您正在使用 linux 系统,那么您需要添加

using namespace std;

低于标题

如果窗口,那么请确保正确放置标题 #include<iostream.h>

#include<string.h>

参考这一点,它的工作完美。

#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;
}

以上答案很好,但如果您不想添加字符串包含,可以使用以下方法

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


return os;
}

使用 c _ str ()将 std: : string 转换为 const char * 。

cout << "String is  : " << text.c_str() << endl ;