Danny
Danny

Reputation: 9614

C++ convert/adding char to string

I'm about to hit the screen with my keyboard as I couldn't convert a char to a string, or simply adding a char to a string.

I have an char array and I want to pick whichever chars I choose in the array to create a string. How do I do that?

string test = "oh my F**king GOD!"
const char* charArray = test.c_str();

string myWord = charArray[0] + charArray[4];

thats how far I got with it. Please help.

Upvotes: 2

Views: 1290

Answers (4)

Joe Tyman
Joe Tyman

Reputation: 1417

You need to also need to remember that a C++ string is quite similar to a vector, while a C string is just array of chars. Vectors have an operator[] and a push_back method. Read more here You use push_back and do not convert to c string. So your code would look like this:

string test = "oh my F**king GOD!"
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);

Upvotes: 0

MoonBun
MoonBun

Reputation: 4402

no need to convert to c_str just:

string test = "oh my F**king GOD!";
string myWord;
myWord += test[0];
myWord += test[4];

Upvotes: 1

sergiol
sergiol

Reputation: 4335

Are you restricted in some way to use C++ functions only? Because, for this purpose I use the old C functions like sprintf

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);

You don't need to use c_str() here.

Upvotes: 5

Related Questions