0

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

Seb
  • 2,929
  • 4
  • 30
  • 73
  • The object latin_str is destroyed on function exit, so return_str will point to invalid memory outside the function. You'll need to allocate it dynamically, and take care of its proper release. – Luchian Grigore Feb 20 '15 at 08:54
  • This link may help you, please visit http://stackoverflow.com/questions/16714278/c-string-encoding-utf8-without-libiconv –  Feb 20 '15 at 08:55

2 Answers2

1

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.

Janick Bernet
  • 20,544
  • 2
  • 29
  • 55
1

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();
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • Thanls jpo38, related to the comment of Janick, do you think we need to change toLatin1 to toUtf8 ? – Seb Feb 20 '15 at 08:53
  • I would say try both and pickup the one that works....and if they both work choose toLocal8Bit ;-) – jpo38 Feb 20 '15 at 08:55
  • issue : error: cannot initialize return object of type 'char *' with an rvalue of type 'const char *' return std::string( str.toLatin1().constData() ).c_str(); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ – Seb Feb 20 '15 at 08:56
  • Sorry. Just make your function return a const char* or cast it using return `const_cast( std::string( str.toLatin1().constData() ).c_str() );` – jpo38 Feb 20 '15 at 08:58
  • The temporary string immediately goes out of scope and is destroyed when the function exits leaving a dangling pointer and the same problem the OP already has. – Retired Ninja Feb 20 '15 at 09:03
  • So I will change my post to return std::string. This is safer. – jpo38 Feb 20 '15 at 09:08