为什么我不能唱一个字符串?

Ata*_*Ata 130 c++ string cout

为什么我不cout string喜欢这个:

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

当我这样做时,我收到以下错误:

错误2错误C2679:二进制'<<':找不到带有'std :: string'类型的右手操作数的运算符(或者没有可接受的转换)c:\ users\mollasadra\documents\visual studio 2008\projects\barnamec\barnamec\barnamec.cpp 67 barnamec**

令人惊讶的是,即使这不起作用:

string text ;
text = "hello"  ;
cout << "String is  : " << text << endl ;
Run Code Online (Sandbox Code Playgroud)

Kir*_*rov 229

你需要包括

#include <string>
#include <iostream>
Run Code Online (Sandbox Code Playgroud)

  • +1:Visual C++中的许多STL头文件(包括<iostream>)引入了`std :: basic_string`类的定义(因为它们间接包含实现定义的<xstring>头文件(*永远不包括那个*)) .虽然这允许您使用字符串类,但相关的`operator <<`在<string>标头本身中定义,因此您必须手动包含它.还依赖于其他标头间接包含`std :: basic_string`的定义在VC++中有效,但它不适用于所有编译器. (54认同)
  • 还有`using namespace std`或`using std :: cout`; `使用std :: endl`; (7认同)
  • 斯文 - 你的评论太棒了!我有一个与这个提问者类似的问题,编译器说运算符>>没有为类型std :: cin和std :: string定义.事实证明我有<iostream>但忘记了<string>.我习惯于使用linux w/gcc,这会抱怨没有定义std :: string.您的评论完全解释了我们为什么会收到有关运营商的投诉.谢谢!! (5认同)
  • 是的,但我想它包括在内,因为`字符串文本没有错误;`编辑(添加错误)也说,这不是问题,而是缺少`string`标题. (2认同)
  • 这有效.我错过了代码中的#include <string>行.谢谢. (2认同)

unp*_*680 11

你需要以std某种方式引用cout的命名空间.例如,插入

using std::cout;
using std::endl;
Run Code Online (Sandbox Code Playgroud)

在函数定义或文件之上.


sep*_*p2k 6

您的代码有几个问题:

  1. WordList没有在任何地方定义.您应该在使用它之前定义它.
  2. 你不能只在这样的函数之外编写代码.你需要把它放在一个函数中.
  3. #include <string>在使用cout或之前,您需要先使用字符串类和iostream endl.
  4. string,coutendl住在std命名空间,所以你不能没有用前缀访问它们std::,除非你使用的using指令,以使它们的范围第一次.