QString to char* conversion

前端 未结 10 1958
予麋鹿
予麋鹿 2020-11-27 02:57

I was trying to convert a QString to char* type by the following methods, but they don\'t seem to work.

//QLineEdit *line=new QLineEdit();{just to describe w         


        
相关标签:
10条回答
  • Qt provides the simplest API

    const char *qPrintable(const QString &str)
    const char *qUtf8Printable(const QString &str)
    

    If you want non-const data pointer use

    str.toLocal8Bit().data()
    str.toUtf8().data()
    
    0 讨论(0)
  • 2020-11-27 03:04

    Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by "it deosn't seem to work".

    0 讨论(0)
  • 2020-11-27 03:09

    It is a viable way to use std::vector as an intermediate container:

    QString dataSrc("FooBar");
    QString databa = dataSrc.toUtf8();
    std::vector<char> data(databa.begin(), databa.end());
    char* pDataChar = data.data();
    
    0 讨论(0)
  • 2020-11-27 03:14

    David's answer works fine if you're only using it for outputting to a file or displaying on the screen, but if a function or library requires a char* for parsing, then this method works best:

    // copy QString to char*
    QString filename = "C:\dev\file.xml";
    char* cstr;
    string fname = filename.toStdString();
    cstr = new char [fname.size()+1];
    strcpy( cstr, fname.c_str() );
    
    // function that requires a char* parameter
    parseXML(cstr);
    
    0 讨论(0)
  • 2020-11-27 03:16

    The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to str.toLocal8Bit().constData().

    0 讨论(0)
  • 2020-11-27 03:16

    If your string contains non-ASCII characters - it's better to do it this way: s.toUtf8().data() (or s->toUtf8().data())

    0 讨论(0)
提交回复
热议问题