QString to char* conversion

前端 未结 10 1938
予麋鹿
予麋鹿 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条回答
  • 2020-11-27 03:17

    Maybe

    my_qstring.toStdString().c_str();

    or safer, as Federico points out:

    std::string str = my_qstring.toStdString();
    const char* p = str.c_str();
    

    It's far from optimal, but will do the work.

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

    EDITED

    this way also works

    QString str ("Something");
    
    char* ch = str.toStdString().C_str();
    
    0 讨论(0)
  • 2020-11-27 03:18

    the Correct Solution Would be like this

       QString k;
       k = "CRAZYYYQT";
       char ab[16];
       sprintf(ab,"%s",(const char *)((QByteArray)(k.toLatin1()).data()) );
       sprintf(ab,"%s",(const char *)((QByteArray)(k.toStdString()).data()));  
       sprintf(ab,"%s",(const char *)k.toStdString().c_str()  );
       qDebug()<<"--->"<<ab<<"<---";
    
    0 讨论(0)
  • 2020-11-27 03:26

    Well, the Qt FAQ says:

    int main(int argc, char **argv)
    {
     QApplication app(argc, argv);
      QString str1 = "Test";
      QByteArray ba = str1.toLocal8Bit();
      const char *c_str2 = ba.data();
      printf("str2: %s", c_str2);
      return app.exec();
    }
    

    So perhaps you're having other problems. How exactly doesn't this work?

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