Lots of people like to reinvent the wheel, so wheels in this world come in all shapes and sizes. As someone barely surviving underneath all these wheels, I often find myself endlessly searching for ways to convert between two of them.

The STL library, being the standard library, is naturally used all over the place when writing C++. The const char * string, having come along from C, is also called upon in many situations. And if, in a moment of madness, you also decide to use Qt, then Qt’s own QString is probably something almost no one can completely avoid.

So type conversion becomes a problem.

Conversions between const char * strings and STL strings are the most common.

const char * => STL: I usually just do

C
const char * s = "hello , world!";
string str(s);
and the assignment is done.

If it’s a parameter, you can also directly call the string constructor.

C
const char * s = "hello const char";
string s1("hello , string1 ");
string s2 = s1 + string(s);

s2 is taken care of just like that.

Note that for string concatenation the above style is not recommended. If conditions allow, writing it like this is better:

C
const char * s = "hello const char";
string s1("hello , string1 ");
s1 += string(s);

string to const char * is even simpler:

C
string str("hello world !");
const char * s = str.c_str();

However, note that this can only be called once in the current stack, and then it will be automatically released by the system. Of course, you can pass it as an argument to some function and call it many times; but once you return, this s can no longer be used. So .c_str() seems specifically designed for type conversion when passing parameters.

The addition of the third wheel, QString

const char * => QString: QString naturally supports it. Like the STL string,

C
const char * s = "hello , world !";
QString qs1(s);
QString qs2 = qs1.append(QString(s));
both methods work.

If a specific encoding is needed, you can also

C
QString qs3= QString(QLatin1String(s));
QString qs4 = QString::fromLocal8Bit(s);

And there are many ways for QString => const char *. The most straightforward is:

C
QString qs1= "Hello , world !";
QByteArray ba = qs1.toLocal8Bit();
const char *s = ba.data();
const char *s2 = ba.constData();

Of course you can also do this:

C
QString qs1= "Hello , world !";
string str = qs1.toStdString();
const char *s= str.c_str();
This actually converts to an STL string first, then to const char *.

References

  1. How can I convert a QString to char* and vice versa?