Seb
Seb

Reputation: 3215

String to char * conversion for special character

I have wrote a simple function in C++/Qt to transform QString to char*.

The function is working fine but I had some issues on some specific character. for example "piña colada" as the QString Parameter is transformed to "pi?a colada". something wrong I think in the toLatin1 conversion.

I want "piña colada" from QString to stay "piña colada" in char *

char *convertQStr2char(QString str) {
    QByteArray latin_str;
    char *return_str;
    latin_str = str.toLatin1();
    return_str = latin_str.data();
    return return_str;
}

Any idea ?

Thanks

Upvotes: 0

Views: 973

Answers (2)

jpo38
jpo38

Reputation: 21514

This works for me. As commented, return type was changed for better memory management:

std::string convertQStr2char(QString str) {
    return std::string( str.toLatin1().constData() );
}

// usage:
std::string temp = convertQStr2char( str );
const char* tempChar = temp.c_str();

Upvotes: 1

Janick Bernet
Janick Bernet

Reputation: 21184

Either latin1 cannot represent the ñ character or when you actually print the character it's in the wrong encoding. What you can try is to use toLocal8Bit instead of toLatin1, that will ensure the character encoding used is the one set on the machine. But better would be to encode using UTF8, so toUtf8, that will preserve any kind of special characters.

And as pointed out in the other answer, apart from the encoding issues, your current code will result in invalid read, too.

Upvotes: 1

Related Questions