【问题标题】:Add character array to const string& in C++ [duplicate]在 C++ 中将字符数组添加到 const string& [重复]
【发布时间】:2017-09-12 19:03:46
【问题描述】:
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 添加到“一些随机文本”中。类似的东西 -

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

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

有什么建议吗?

【问题讨论】:

  • 可以使用std::stringstream,或者将第一个字符串封装在构造函数中...
  • 或者使用 std::string 文字
  • C++14 酷猫使用""s + "Some Random text" + stringToAdd; 注意内置的用户定义文字。与 Java 中的 + 可憎不同,这不是杂牌。
  • @Charles - 你到底是怎么建议的?
  • @Bathsheba - 这似乎修复了错误,但我没有得到这个概念。如果你能解释一下。

标签: c++ arrays string pointers character


【解决方案1】:

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

这是因为在这种情况下,+ 运算符的两边都是指针。

使用

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);

【讨论】:

  • 这是关闭的,所以我无法回答,但请随意以 C++14 的方式搞砸:请参阅我的问题评论。不错的答案,尽管如此,请投赞成票。
  • @Bathsheba,感谢您的建议。希望修改后的表达式仍然有效。
  • 它比我拥有它的方式更好。
【解决方案2】:
auto MethodCalledHere(std::string inputParameter) {
    inputParameter.append(stringToAdd, 
                          stringToAdd + std::strlen(stringToAdd));
    return inputParameter;
}

【讨论】:

    猜你喜欢
    • 2012-10-04
    • 2022-01-10
    • 1970-01-01
    • 2015-11-07
    • 2016-04-09
    • 2012-12-15
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多