2012-05-29 74 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";