将QString转换为char*

27

可能重复:
QString转char*的转换方法

我有一个函数(STL中的fopen)需要使用计算机上的路径作为char*参数,但是我必须在这个位置使用QString,所以它不能工作。

如何将QString转换为char *以解决此问题?

2个回答

52

请看如何将QString转换为char *,反之亦然?

In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:

https://doc.qt.io/qt-5/qstring.html#toLatin1 https://doc.qt.io/qt-5/qbytearray.html#data

See the following example for a demonstration:

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

Note that it is necessary to store the bytearray before you call data() on it, a call like the following

const char *c_str2 = str2.toLatin1().data();

will make the application crash as the QByteArray has not been stored and hence no longer exists

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:

QString string = QString(QLatin1String(c_str2)) ;

See the documentation:

https://doc.qt.io/qt-5/qlatin1string.html

当然,我发现有另一种方法可以从之前的SO回答中得到信息:
QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

9
我认为措辞需要改变。语句 const char *c_str2 = str2.toLatin1().data(); 应该可以正常工作。不幸的是,分号后由 toLatin1() 创建的临时 QByteArray 已被销毁,因此 c_str2 现在具有无效指针。相反,您可以在调用中使用它 doStuff(str2.toLatin1().data()); 因为 QByteArray 直到 ';' 才被销毁。因此:printf("str2: %s", str2.toLatin1().data()); 应该没问题。 - Martin York
@Martin:我只是引用Qt的话。 - user195488
2
这个问题让我调试了半天,原因是底层的 QByteArray 被销毁了。虽然必须要存储这个字节数组,但它真的很麻烦。 - mpenkov
Loki的评论似乎很准确。我经常使用someFunction(myQString.toUtf8().constData()); 它可以正常工作,但是如果您尝试使用char * myCString = myQString.toUtf8().constData(); 然后使用myCString,你会得到一个C字符串,有时工作,有时不工作,这取决于是否访问其内容的QByteArray仍然有效当您通过C指针访问。在这里一定要小心! - Vern Jensen
我希望得到 char* 而不是 const char*。 - user889030
注意:toLocal8Bit 如果此字符串包含任何无法在locale中编码的字符,则返回的字节数组是未定义的。这些字符可能会被抑制或替换为其他字符。-- 这听起来只有在你事先知道QString仅包含有效的Latin1字符时才有效。 - jrh

3

你可以使用QFile而不是std::fstream。

QFile           file(qString);

或者将QString转换为char*,如下所示:

std::ifstream   file(qString.toLatin1().data());

QString 是使用 UTF-16 编码的,因此在这里进行了转换为 Latin1(),但 QString 还有一些其他的转换方式,包括 toUtf8()(请检查您的文件系统,它可能使用 UTF-8)。

如@0A0D所述:不要将 char* 存储在变量中而不获取 QByteArray 的本地副本。

char const*      fileName = qString.toLatin1().data();
std::ifstream    file(fileName);  // fileName not valid here.

这是因为toLatin1()返回一个QByteArray对象。由于它实际上没有绑定到变量,它是一个在表达式结束时被销毁的临时对象。因此,在这里调用data()返回一个指向内部结构体的指针,在';'之后该结构体将不再存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接