Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred conversion from char (not char*) to std::string

I have a char, a plain old character, that I would like to turn into an std::string. std::string(char) doesn't exist of course. I could create an char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast, but even that seems too verbose for this simple task. So what's the preferred way?

like image 641
pythonic metaphor Avatar asked Jan 18 '11 20:01

pythonic metaphor


People also ask

Can you convert char * to string?

We can convert a char to a string object in java by using String. valueOf(char[]) method.

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

Is char * a string?

char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.


2 Answers

std::string has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use:

std::string str(1, ch); 
like image 71
Daniel Gallagher Avatar answered Sep 17 '22 22:09

Daniel Gallagher


To add to the answer, you can simply use initializer list

std::string str = {ch}; 
like image 42
Gaurav Pant Avatar answered Sep 19 '22 22:09

Gaurav Pant