2011-11-28 32 views
6

例如字符串,如果我有這個小功能:如何返回包含字符串/ int變量會生成

string lw(int a, int b) {  
    return "lw $" + a + "0($" + b + ")\n"; 
} 

....和撥打電話lw(1,2)在我的主要功能我想它返回"lw $1, 0($2)"

但我不斷收到一個錯誤:invalid operands of types ‘const char*’ and ‘const char [11]’ to binary ‘operator+’

我在做什麼錯?我幾乎從類中複製了一個例子,並將其改爲適合我的功能。

回答

10

您試圖將整數連接到字符串,並且C++不能轉換這些不同類型的值。最好的辦法是使用std::ostringstream構建結果字符串:

#include <sstream> 

// ... 

string lw(int a, int b) 
{ 
    ostringstream os; 
    os << "lw $" << a << "0($" << b << ")\n"; 
    return os.str(); 
} 

如果你有Boost,您可以使用Boost.Lexical_cast

#include <boost/lexical_cast.hpp> 

// ... 

string lw(int a, int b) 
{ 
    return 
     string("lw $") + 
     boost::lexical_cast<std::string>(a) + 
     string("0($") + 
     boost::lexical_cast<std::string>(b) + 
     string(")\n"); 
} 

與C++ 11以後有

現在是std::to_string

string lw(int a, int b) 
{ 
    return 
     string("lw $") + 
     std::to_string(a) + 
     string("0($") + 
     std::to_string(b) + 
     string(")\n"); 
} 
+0

工作得很好,謝謝。 – Rima

+0

雖然你的第一句話是正確的,但由於OP沒有連接'std :: string's,所以這個問題也完全不相關。 –

+0

@MarkB你說得對。希望更新的答案更清楚。 –

1

您不能將字符串文字(如「hello」)添加到整數。這是編譯器對你說的。這是你的問題的部分答案。請參閱如何在另一篇文章中完成您想要的內容。

+0

事實上,您*可以*將char和char *都添加到整數。只是大部分時間根本不會做你想要的。 –

+0

@MarkB我會改進我的答案。 – Beginner

2
#include <sstream> 

string lw(int a, int b) {  
    std::string s; 
    std::stringstream out; 
    out << "lw $" << a << "0($" << b << ")" << endl; 
    s = out.str(); 
    return s; 
} 
+0

工程,但你支付了out.str()''多餘的本地副本......爲什麼要做這個副本? (另外我會指出一些我直到最近才學到的東西,那就是在一般情況下'endl'不是''\ n「'的同義詞 - 它刷新流,所以我停止了「整理」使用'「\ n」'使用'endl' ...) – HostileFork

2

使用ostringstream:

#include <sstream> 
... 
string lw(int a, int b) { 
    std::ostringstream o; 
    o << "lw $" << a << "0($" << b << ")\n"; 
    return o.str(); 
} 
0

要理解這個問題,你要知道,在C++中,字符串文字像"lw $"作爲const char[]視爲從C語言繼承。然而,這意味着你只能得到爲數組定義的運算符,或者在這種情況下是數組降級到指針的情況。

所以會發生什麼是你有一個字符串文字,然後添加一個整數,創建一個新的指針。然後,您嘗試添加另一個字符串文字,該文字再次降級爲char*。您不能將兩個指針相加,然後生成您所看到的錯誤。

您試圖將整數格式化爲帶有一些分隔文本的字符串格式。在C++中,這樣做的規範方式是使用字符串流:

#include <sstream> 

string lw(int a, int b) 
{ 
    std::ostringstream os; 
    os << "lw $" << a << "0($" << b << ")\n"; 
    return os.str(); 
}