2012-05-29 75 views
1

我试图创建一个指向文件的字符串,并正在此错误:错误连接字符串(C++)时

.../testApp.cpp:75: error: invalid operands of types 'const char*' and 'const char [5]' to binary 'operator+'

这里是有问题的行:

​​

这看起来像一个相当简单的问题,但它让我困惑。我还包括字符串标头:

#include <string> 
using namespace std 
+0

'i'的类型是什么? – hmjd

+0

@hmjd我是一个int – Miles

回答

1

您试图连接字符串文字,就好像它们是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::stringint

一个解决问题的方法是使用std::stringstream,这需要任何operator<<std::cout可以采取:

std::stringstream spath; 
spath << "images/" << i << ".png"; 
std::string path = spath.str(); 
+0

_technicially_字符串文字将与std :: string,并相互(尽管使用不同的语法)连接。你应该改写第1部分。 –

+0

谢谢,@MooingDuck。我更新了我的帖子。 –

3

使用stringstream相反,std::string不支持现成的架子格式为整数。

std::stringstream ss; 
ss << "images/" << i << ".png"; 
std::string path = ss.str(); 
4

您需要i转换为std::string

string path = "images/" + boost::lexical_cast<string>(i) + ".png"; 

对于其他的方法来转换一个intstd::string看到Append an int to a std::string

4

boost::format

std::string str = (boost::format("images/%d.png") % i).str(); 

boost::format(FORMATTED_STIRNG) % .. %.. %..用于格式化字符串处理,请参见wiki。此函数为您提供了一种特殊的提升格式,您需要使用它的.str()成员函数将其转换为std :: string。

+0

请不要只发布一行代码。解释一下。 -1 – Manishearth

+0

对不起,我认为语法很明显。但我现在添加了解释。 – guinny

+0

Undownvote-upvoted。尝试为您的未来帖子做到这一点:) – Manishearth

0

引述所有其他的答案,是的,std::string没有内置在支持附加的整数。但是,您可以添加运算符来做到这一点:

template<typename T> 
std::string operator +(const std::string &param1, 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!"; 
+0

我想在使用它之前进行彻底测试,这可能会导致证明定义良好的行为突然得到一个模糊性错误。 –

1

用C++ 11我们得到一组to_string函数,可以帮助将内置的数字类型转换为std :: string。你可以在你的转换中使用它:

string path = "images/" + to_string(i) + ".png";