如何附加一个字符到std :: string? [英] How to append a char to a std::string?

查看:229
本文介绍了如何附加一个字符到std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下失败,并显示错误 prog.cpp:5:13:error:从char无效转换为const char *'

The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’

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

我也试过,下面的代码在运行时编译但随机运行: / p>

I also tried, the following, which compiles but behaves randomly at runtime:

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

对不起,这个蠢的问题,但我搜索google,可以看到只是char array to char ptr,char ptr to char array等。

Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.

推荐答案

y += d;

我会使用 + = 命名函数。

这篇关于如何附加一个字符到std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆