下面的代码会出现错误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到字符数组”,等等。


当前回答

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

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

其他回答

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

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

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

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

除了前面提到的其他构造函数外,其中一个字符串构造函数取一个char和该char的重复次数。 你可以用它来追加一个字符。

std::string s = "hell";
s += std::string(1, 'o');

尝试使用d作为指针 y.append (* d)

还添加了插入选项,还没有提到。

std::string str("Hello World");
char ch;

str.push_back(ch);  //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above