260

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;
}

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;
}

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.

2
  • 1
    a compiler error yes..I forgot what the error is, but it's reasonable. Commented Sep 24, 2009 at 14:33
  • 4
    You have better answers below, but you can make you second example working like this char d[2] = {'d', 0}; or just char d[2] = "d"; Basically, you need a 0 to terminate your c-style string you pass to append Commented Sep 24, 2009 at 15:17

15 Answers 15

320
y += d;

I would use += operator instead of named functions.

Sign up to request clarification or add additional context in comments.

5 Comments

why do you consider += better than push_back? Is it just less typing or do you have another reason?
It's less typing. In gcc, basic_string::operator+= is just a call in push_back.
It is more natural IMO for strings. push_back is container function, and a string is a specialized one in STL :)
Let's turn that question around: Why do you consider push_back better than +=? In my opinion, += is clear and concise.
You want to be careful with this because if you get into the habit, this will compile just fine if y is a char* instead of std::string. It'd add d characters to the pointer y.
107

Use push_back():

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

Comments

25

To add a char to a std::string var using the append method, you need to use this overload:

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

Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

s.append(1, d);

not

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

Or the simpliest way :

s += d;

4 Comments

I think using sizeof is not semantically correct here (even though it happens to work as sizeof(char) is always one). The append method is naturally more useful if you want to append more copies of the same character!!!!!!!!!!
Why are you using sizeof(char) instead of 1? You want to append exactly one repetition of d, so just say that. Using sizeof here is misleading since it suggests that one has to tell append the byte size of the data type used (which is not the case).
As Unclebens said, the append method is really more useful when adding the same character many times.
append() is not useful to append a single char which is what the op asked for.
13

In addition to the others mentioned, one of the string constructors take a char and the number of repetitions for that char. So you can use that to append a single char.

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

1 Comment

This is neither faster nor better in any other way than += or push_back().
12

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an 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;

According to this test, results are :

     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'

Conclusion

+= seems more understandable, but if you mind about speed, use append

3 Comments

For such an answer to be meaningful, you should a least tell what compiler are you using, because such things might vary a LOT. Telling about your processor can be great too, to get a rough estimate on the actual impact this might have.
I used visual studio 2015. I will look for gcc to do some other tests.My processor is i7, 8 hearts, 2.20 Ghz....But whatever is my processor it will have no impact on std::string implementation...except if some of these method are multithreaded and someothers not.
Sometimes it has an impact, especially if you are showing timings in milliseconds. Instead you could show in percentage relative to fastest method(So actual processor speed is irrelevant) Also move that data from the comment to your answer, this is just general StackExchange etiquette. Otherwise nice answer.
6

Try the += operator link text, append() method link text, or push_back() method link text

The links in this post also contain examples of how to use the respective APIs.

Comments

4

Supplementary answer, because apparently this answer with many upvotes is suggesting to use push_back('c') while another is suggesting not to. Since both answers were a bit old, let's have an update.

Using the STL, libstdc++ by the GNU, the performance of the following 5 methods of appending a char to a std::string will be tested: str.append(), str += 'c', str.resize(str.size() + 1, 'c'), str.push_back('c'), and str.insert(str.end(), 1, 'c').

Let t be the minimum time used amongst the operations, the results are as follows:

params \ cpu_time (4dp) append() += resize() push_back() insert()
optim = none
compiler = Clang 11.0
std = c++11
2.6255
1.1t
2.4826
t
3.3396
1.3t
2.4759
t
4.5967
2t
optim = none
compiler = Clang 15.0
std = c++20
14.1841
1.5t
9.3077
t
15.7846
1.7t
9.7907
1.1t
27.1050
2t
optim = O3
compiler = Clang 11.0
std = c++11
19.1018
2t
9.9812
t
25.1597
2.5t
10.0466
t
17.5578
2t
optim = O3
compiler = Clang 15.0
std = c++20
9.9465
t
9.8468
t
9.9519
t
9.8686
t
9.9145
t

The += operator and push_back() are consistently the quickest method, followed by append() (1.1t - 2t), resize() (1.3t - 2.5t), and insert() (2t)

Comments

3

the problem with:

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

is that you have to have the 'd' as opposed to using a name of a char, like char d = 'd'; Or am I wrong?

1 Comment

I just tried it and it worked fine. I have char c = 'd' and I can do y.push_back(c) without issue. So there is no problem with std::string::push_back() (except that it's longer than +=).
3

Also adding insert option, as not mentioned yet.

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

Comments

2
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
}

Note that in all of these examples you could have used a character literal directly: y += 'd';.

Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'}; didn't work, but char d[2] = { 'd'}; (note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal can be appended: y.append(d);.

Comments

2

there are three ways to do this:
for example, we have code like this:
std::string str_value = "origin";
char c_append = 'c';

  1. we usually use push_back().
    str_value.push_back(c)
  2. use += .
    str_value += c
  3. use append method.
    str_value.append(1,c)
    And you can learn more about the methods of string from http://www.cplusplus.com/reference/string/string/

1 Comment

Does not seem to be much better than @MooingDuck 's answer
1

Try using the d as pointer y.append(*d)

2 Comments

That's dangerous as a single char is no string and has no null-terminator. Doing this causes undefined behaviour.
This is just wrong. *d means de-reference pointer d which is a syntax error since d isn't a pointer.
1

I found a simple way... I needed to tack a char on to a string that was being built on the fly. I needed a char list; because I was giving the user a choice and using that choice in a switch() statement.

I simply added another std::string Slist; and set the new string equal to the character, "list" - a, b, c or whatever the end user chooses like this:

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

Complexity may be cool but simplicity is cooler. IMHO

Comments

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

Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.

Comments

-1

If you are using the push_back there is no call for the string constructor. Otherwise it will create a string object via casting, then it will add the character in this string to the other string. Too much trouble for a tiny character ;)

1 Comment

operator +=(char c); is overloaded for strings. In fact, the string constructor doesn't accept one character, see Brian answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.