2017-09-12 180 views
1
char stringToAdd[4097] = ""; 

// some manipulations on stringToAdd to add some value to it. 

if(stringToAdd[0] != '\0') { 
response = MethodCalledHere("Some Random text"); 
} 

MethodCalledHere(const String& inputParameter) { 
// some method definition here. 
} 

我已經到stringToAdd添加到「一些隨機文本」。喜歡的東西 -字符數組添加到常量字符串和C++中

response = MethodCalledHere("Some Random text" + stringToAdd); 

但是這給了我錯誤 「+」不能添加兩個指針。

有什麼建議嗎?

+0

你可以用'的std :: stringstream',或封裝第一串在構造函數... – Charles

+0

或者使用'的std :: string'文字 – StoryTeller

+1

的C++ 14個酷貓用' 「」 s +「一些隨機文本」+ stringToAdd;'注意內置的用戶定義文字。不像Java中的+可憎,這不是一個混亂。 – Bathsheba

回答

0
auto MethodCalledHere(std::string inputParameter) { 
    inputParameter.append(stringToAdd, 
          stringToAdd + std::strlen(stringToAdd)); 
    return inputParameter; 
} 
2

但是這給了我錯誤「+」不能添加兩個指針。

這是因爲在這種情況下,+運算符的雙方都是指針。

使用

response = MethodCalledHere(std::string("Some Random text") + stringToAdd); 

如果你的函數期望char const*,那麼,你可以構造一個std::string,然後再使用std:string::c_str()

std::string s = std::string("Some Random text") + stringToAdd; 
response = MethodCalledHere(s.c_str()); 

如果你能使用C++ 14,可以使用字符串字面量(感謝是由於@Bathsheba您的建議)。

response = MethodCalledHere("Some Random text"s + stringToAdd); 
+1

這是封閉的,所以我無法回答,但可以用C++ 14的方式自由發言:請參閱我的問題評論。儘管如此,尼斯的回答有點贊成。 – Bathsheba

+1

@Bathsheba,謝謝你的建議。希望修改後的表達式仍然有效。 –

+0

這比我擁有的方式要好。 – Bathsheba