How to append a char to a std::string?

C++String

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

y += d;

I would use += operator instead of named functions.

Solution 2 - C++

Use push_back():

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

Solution 3 - C++

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;

Solution 4 - C++

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

Solution 5 - C++

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

Solution 6 - C++

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.

Solution 7 - C++

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?

Solution 8 - C++

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

Solution 9 - C++

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

Solution 10 - C++

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.

Solution 11 - C++

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

Solution 12 - C++

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

Solution 13 - C++

>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/

Solution 14 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYana D. NugrahaView Question on Stackoverflow
Solution 1 - C++Khaled AlshayaView Answer on Stackoverflow
Solution 2 - C++Ferdinand BeyerView Answer on Stackoverflow
Solution 3 - C++Patrice BernassolaView Answer on Stackoverflow
Solution 4 - C++Brian R. BondyView Answer on Stackoverflow
Solution 5 - C++Hugo ZevetelView Answer on Stackoverflow
Solution 6 - C++Michael BergView Answer on Stackoverflow
Solution 7 - C++Alex SpencerView Answer on Stackoverflow
Solution 8 - C++Mooing DuckView Answer on Stackoverflow
Solution 9 - C++Gopesh BharadwajView Answer on Stackoverflow
Solution 10 - C++Ioan StefView Answer on Stackoverflow
Solution 11 - C++2ndlessView Answer on Stackoverflow
Solution 12 - C++Charles HView Answer on Stackoverflow
Solution 13 - C++BrookView Answer on Stackoverflow
Solution 14 - C++progicianView Answer on Stackoverflow