我试图创建一个指向文件的字符串,并正在此错误:错误连接字符串(C++)时
.../testApp.cpp:75: error: invalid operands of types 'const char*' and 'const char [5]' to binary 'operator+'
这里是有问题的行:
这看起来像一个相当简单的问题,但它让我困惑。我还包括字符串标头:
#include <string>
using namespace std
我试图创建一个指向文件的字符串,并正在此错误:错误连接字符串(C++)时
.../testApp.cpp:75: error: invalid operands of types 'const char*' and 'const char [5]' to binary 'operator+'
这里是有问题的行:
这看起来像一个相当简单的问题,但它让我困惑。我还包括字符串标头:
#include <string>
using namespace std
您试图连接字符串文字,就好像它们是std::string
对象。他们不是。在C++中,字符串文字的类型是const char[]
,而不是std::string
。
要连接两个字符串文字,接下来将它们彼此无操作员:
const char* cat = "Hello " "world";
要连接两个std::string
对象,请使用operator+(std::string, std::string)
:
std::string hello("hello ");
std::string world("world\n");
std::sting cat = hello + world;
还有一个operator+
加盟字符串文字和std::string
:
std::string hello("hello ");
std::string cat = hello + "world\n";
没有operator+
需要std::string
和int
。
一个解决问题的方法是使用std::stringstream
,这需要任何operator<<
是std::cout
可以采取:
std::stringstream spath;
spath << "images/" << i << ".png";
std::string path = spath.str();
_technicially_字符串文字将与std :: string,并相互(尽管使用不同的语法)连接。你应该改写第1部分。 –
谢谢,@MooingDuck。我更新了我的帖子。 –
使用stringstream
相反,std::string
不支持现成的架子格式为整数。
std::stringstream ss;
ss << "images/" << i << ".png";
std::string path = ss.str();
您需要i
转换为std::string
:
string path = "images/" + boost::lexical_cast<string>(i) + ".png";
对于其他的方法来转换一个int
为std::string
看到Append an int to a std::string
或boost::format
:
std::string str = (boost::format("images/%d.png") % i).str();
boost::format(FORMATTED_STIRNG) % .. %.. %..
用于格式化字符串处理,请参见wiki。此函数为您提供了一种特殊的提升格式,您需要使用它的.str()
成员函数将其转换为std :: string。
请不要只发布一行代码。解释一下。 -1 – Manishearth
对不起,我认为语法很明显。但我现在添加了解释。 – guinny
Undownvote-upvoted。尝试为您的未来帖子做到这一点:) – Manishearth
引述所有其他的答案,是的,std::string
没有内置在支持附加的整数。但是,您可以添加运算符来做到这一点:
template<typename T>
std::string operator +(const std::string ¶m1, const T& param2)
{
std::stringstream ss;
ss << param1 << param2;
return ss.str();
}
template <typename T>
std::string operator +(const T& param1, const std::string& param2) {
std::stringstream ss;
ss << param1 << param2;
return ss.str();
}
template <typename T>
std::string& operator +=(std::string& param1, const T& param2)
{
std::stringstream ss;
ss << param1 << param2;
param1 = ss.str();
return param1;
}
唯一真正的缺点,这是你必须先投下的文字之一为一个字符串,像这样:
string s = string("Hello ") + 10 + "World!";
我想在使用它之前进行彻底测试,这可能会导致证明定义良好的行为突然得到一个模糊性错误。 –
用C++ 11我们得到一组to_string
函数,可以帮助将内置的数字类型转换为std :: string。你可以在你的转换中使用它:
string path = "images/" + to_string(i) + ".png";
'i'的类型是什么? – hmjd
@hmjd我是一个int – Miles