![](/img/trans.png)
[英]C++ I cannot cout one string while i successfully cout an another string
[英]Why I cannot cout a string?
为什么我不能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\项目\barnamec\barnamec\barnamec.cpp 67 barnamec**
令人惊讶的是,即使这样也不起作用:
string text ;
text = "hello" ;
cout << "String is : " << text << endl ;
你需要包括
#include <string>
#include <iostream>
您需要以某种方式引用 cout 的命名空间std
。 例如,插入
using std::cout;
using std::endl;
在您的 function 定义或文件之上。
您的代码有几个问题:
WordList
没有在任何地方定义。 你应该在使用它之前定义它。cout
或endl
之前,您需要先#include <string>
才能使用字符串 class 和 iostream 。string
, cout
和endl
存在于std
命名空间中,因此如果不使用std::
前缀就无法访问它们,除非您使用using
指令首先将它们带入 scope 。以上答案很好,但如果您不想添加字符串包含,您可以使用以下
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 ;
您不必明确引用std::cout
或std::endl
。
它们都包含在namespace std
中。 using namespace std
而不是使用 scope 解析运算符::
每次都更容易和更清洁。
#include<iostream>
#include<string>
using namespace std;
如果您使用的是 linux 系统,那么您需要添加
using namespace std;
下面的标题
如果 windows 则确保正确放置标题#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.