How to append a char to a std::string?
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.
Solution 1:
y += d;
I would use +=
operator instead of named functions.
Solution 2:
Use push_back()
:
std::string y("Hello worl");
y.push_back('d')
std::cout << y;
Solution 3:
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:
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:
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