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


当前回答

我通过将它们运行到一个大循环中来测试这几个命题。 我使用microsoft visual studio 2015作为编译器,我的处理器是i7, 8Hz, 2GHz。

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

根据本次试验,结果为:

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

结论

+=似乎更容易理解,但如果您介意速度,请使用append

其他回答

要使用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方法():

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

我找到了一个简单的方法… 我需要将一个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());

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

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);。

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