char transfer to string

Suppose we have a :

1) char out;
which is in a "for" loop and each time iteration goes on "char out" receives a new value as a letter. So, "char out" can be a, b, c etc. A letter each time.

2) string output;

What we need is that the letter in "char out" to be transfered to "string output", so that in the end we will have "string output" which will contain text composed of all the letters received from "char out".

The question is: how this can be done?

I tried function output.insert(); it does not work in this case.

I tried also the method below, however it also does not work :
char out;
string output(out);

This also does not work :
char out;
string output(out, 1); // assuming that the size is 1

Thank you in advance.
You can add char values to the end of a string with push_back()
http://www.cplusplus.com/reference/string/string/push_back/

output.push_back(out);
First you need to declare the output string before the loop.

You can use the insert function to add a character to the string but then you also need to specify the position.

1
2
// Add the out character to the end of the output string.
output.insert(output.end(), out);


Appending (adding to the end) can also be done using the += operator.

 
output += out;
output.push_back(out);

output.insert(output.end(), out);

both worked, thank you.
I did not know that these functions (push_back, pop_back) work for strings also, I used them for vectors.
Read up on strings. They have many more functions.

http://www.cplusplus.com/reference/string/string/

It's a good idea, when you make use of a class, to read up on what it has to offer.
Topic archived. No new replies allowed.