首页 文章

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

提问于
浏览
123

为什么我不能 cout string 这样:

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

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

错误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 ;

6 回答

  • 6

    你需要包括

    #include <string>
    #include <iostream>
    
  • -1

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

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

    在函数定义或文件之上 .

  • 10

    您的代码有几个问题:

    • WordList 未在任何地方定义 . 您应该在使用它之前定义它 .

    • 你不能只在这样的函数之外编写代码 . 你需要把它放在一个函数中 .

    • 在使用 coutendl 之前,您需要 #include <string> 才能使用字符串类和iostream .

    • stringcoutendl 位于 std 命名空间中,因此除非使用 using 指令将它们首先放入范围,否则无法使用_2394350前缀来访问它们 .

  • 1

    以上答案很好,但如果您不想添加字符串include,则可以使用以下内容

    ostream& operator<<(ostream& os, string& msg)
    {
    os<<msg.c_str();
    
    return os;
    }
    
  • 219

    您不必明确引用 std::coutstd::endl .
    它们都包含在 namespace std 中 . using namespace std 而不是使用范围解析操作符 :: 每次使更容易和更清洁 .

    #include<iostream>
    #include<string>
    using namespace std;
    
  • -2

    如果您使用的是Linux系统,则需要添加

    using namespace std;

    Headers 下方

    如果windows然后确保你正确放置 Headers #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;
    }
    

相关问题