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


当前回答

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

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

其他回答

问题在于:

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

你必须使用d而不是使用char的名字,比如char d = 'd';还是我错了?

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

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

int main()
{
  char d = 'd';
  std::string y("Hello worl");

  y += d;
  y.push_back(d);
  y.append(1, d); //appending the character 1 time
  y.insert(y.end(), 1, d); //appending the character 1 time
  y.resize(y.size()+1, d); //appending the character 1 time
  y += std::string(1, d); //appending the character 1 time
}

请注意,在所有这些示例中,您都可以直接使用字符文字:y += 'd';。

第二个例子几乎是可行的,但原因与此无关。Char d[1] = {'d'};没有工作,但char d[2] = {'d'};(注意数组的大小为2)将与const char* d = "d";大致相同,并且可以追加字符串字面量:y.p append(d);。

要使用append方法向std::string var添加一个char,你需要使用以下重载:

std::string::append(size_type _Count, char _Ch)

编辑: 你是对的,我误解了在上下文帮助中显示的size_type参数。这是要加的字符数,正确的方法是

s.append(1, d);

not

s.append(sizeof(char), d);

或者用最简单的方式:

s += d;

如果使用push_back,则不会调用string构造函数。否则,它将通过强制转换创建一个字符串对象,然后将该字符串中的字符添加到另一个字符串中。对一个小角色来说太麻烦了;)