相关疑难解决方法(0)

如何将char附加到std :: string?

以下因错误而失败 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;
}
Run Code Online (Sandbox Code Playgroud)

我也试过,以下,编译但在运行时随机行为:

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

抱歉这个愚蠢的问题,但我搜索了谷歌,我能看到的只是"char char to char ptr","char ptr to char array"等.

c++ string

159
推荐指数
6
解决办法
29万
查看次数

c ++字符串append和operator + =之间的区别

两条线之间有明显的区别吗?我的同事说使用+ =是"更快"但我不明白他们为什么应该有所不同:

string s1 = "hello";
string s2 = " world";

// Option 1
s1 += s2;

// Option 2
s1.append(s2);
Run Code Online (Sandbox Code Playgroud)

为了澄清,我不是在问两个函数之间的用法差异 - 我知道它append()可以用于更广泛的用途,而且operator +=更专业.我关心的是如何处理这个特定的例子.

c++ string string-concatenation

7
推荐指数
2
解决办法
3160
查看次数

标签 统计

c++ ×2

string ×2

string-concatenation ×1