The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’
int main()
{
char d = \'d\';
std::s
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);
.
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.
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
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?
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
Use push_back()
:
std::string y("Hello worl");
y.push_back('d')
std::cout << y;