下面的代码会出现错误prog.cpp:5:13: error:无效的从' char '到' const char* '的转换

int main()
{
  char d = 'd';
  std::string y("Hello worl");
  y.append(d); // Line 5 - this fails
  std::cout << y;
  return 0;
}

我也尝试了,下面,它编译,但在运行时随机行为:

int main()
{
  char d[1] = { 'd' };
  std::string y("Hello worl");
  y.append(d);
  std::cout << y;
  return 0;
}

对不起,这个愚蠢的问题,但我已经搜索了谷歌,我能看到的只是“字符数组到字符ptr”,“字符ptr到字符数组”,等等。


当前回答

y += d;

我将使用+=运算符而不是命名函数。

其他回答

试试+=操作符链接文本, Append()方法链接文本, 或push_back()方法链接文本

本文中的链接还包含了如何使用相应api的示例。

我找到了一个简单的方法… 我需要将一个char附加到正在动态构建的字符串上。我需要一个字符列表;因为我给了用户一个选择,并在switch()语句中使用了这个选择。

我只是简单地添加了另一个std::string Slist;并将新字符串设置为字符"list" - a, b, c或任何最终用户选择的字符,如下所示:

char list;
std::string cmd, state[], Slist;
Slist = list; //set this string to the chosen char;
cmd = Slist + state[x] + "whatever";
system(cmd.c_str());

复杂也许很酷,但简单更酷。恕我直言

y += d;

我将使用+=运算符而不是命名函数。

有三种方法: 例如,我们有这样的代码: Std::string str_value = "origin"; Char c_append = 'c'; 我们通常使用push_back()。 str_value.push_back (c) 使用+=。 Str_value += c 使用追加方法。 str_value.append (1 c) 你可以从http://www.cplusplus.com/reference/string/string/了解更多关于string的方法

str.append(10u,'d'); //appends character d 10 times

注意,我写的是10u,而不是10,表示我想附加字符的次数;将10替换为任何数字。