How do you convert a QString
to char
? some easy and understandable way?
It's to understand better thanks.
How do you convert a QString
to char
? some easy and understandable way?
It's to understand better thanks.
QString
has the toStdString()
method that returns a std::string
. Obtaining a char
from this object is trivial:
QString cadena = "Hola";
std::string cadenaStd = cadena.toStdString();
char c = cadenaStd[0];
std::cout << c;
Greetings.
How do you convert a
QString
tochar
?
There is no possible conversion of a complex type (in this case QString
) to a fundamental type (in this case char
), your question is similar to " How does a Coche in a Piston ? ".
While it is true that Cars have engines and engines have Pistons, a Piston is a part of the Car.
You can not convert a Car into a Piston although you will use Pistons to build your Car ... parallel you can not convert a QString
into a char
although you will use char
as a piece of QString
.
So I guess you really wanted to ask:
How do I access the
char
of aQString
?
So I will base my answer on that assumption.
QString
is created as a class analogous to the class string ; so it has similar, equivalent or exactly the same methods.
Use the index operator (access by square brackets [
and ]
). Given the almost complete equivalence between QString
and std::string
both objects have that operator and is used in the same way.
So, in the following example, both show @
when using the
operator brackets on the fifth position:
QString q_mail("[email protected]");
std::string stl_mail("[email protected]");
std::cout << "quinto caracter: " << q_mail[4];
std::cout << "quinto caracter: " << stl_mail[4];
Well, assuming you use Qt 5.x, it's relatively simple.
To convert one to one (or some) of the characters of a QString
you should use something like the following code:
QString ejemplo="ejemplo";
std::cout << ejemplo.at(0).toLatin1(); //funcion at devuelve el tipo de dato Qchar de la cadena en la posicion 0
//y .toLatin1() devuelve el caracter en dato char.
On the other hand, if you want to convert all the QString
, a faster option is to use .toLatin1()
on the object QString
.
QString ejemplo2="ejemplo2";
ejemplo2.toLatin1(); //esta funcion devuelve un QByteArray
A QByteArray
is roughly a class that serves as a dynamic array of char
(you can concatenate, add, remove, etc.), without the complexity of dynamic memory.
Also it must be said that from a QByteArray
you can get the data as type char
if you use the functions data
or constData
.
QByteArray ejemploByteArray=ejemplo2.toLatin1();
ejemploByteArray.constData(); //devuelve un puntero constante a un data *char, por ejemplo si solo es un parametro de lectura
ejemploByteArray.data(); //devuelve un puntero *char, este si modificable, por lo que si lo manipulas cambiaras tambien los datos de QByteArray, por lo que aqui si hay que tener cuidado.