将字符数组添加到 const string&in C++

Add character array to const string& in C++

本文关键字:string in C++ const 字符 数组 添加      更新时间:2023-10-16
char stringToAdd[4097] = ""; 
// some manipulations on stringToAdd to add some value to it. 
if(stringToAdd[0] != '') { 
response = MethodCalledHere("Some Random text");
}
MethodCalledHere(const String& inputParameter) {
 // some method definition here.
}

我已经将StringToAdd添加到"一些随机文本"中。像 -

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

但这给了我错误' '不能添加两个指针。

有什么建议?

,但这给了我错误的错误,即" "无法添加两个指针。

那是因为在这种情况下,+操作员的两侧都是指针。

使用

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);
auto MethodCalledHere(std::string inputParameter) {
    inputParameter.append(stringToAdd, 
                          stringToAdd + std::strlen(stringToAdd));
    return inputParameter;
}