我正在读取一个xml文件,并试图将数据解析为双精度。它正在读取数据并在应用程序输出中显示适当的字符串,但不会从字符串转换为双精度字符串。这是进行转换的代码部分。
if ( !(imgDur = QString ( xmlReader->readElementText() ).toDouble()) ){
imgDur = 10;
}
这将返回数字0。我得到零错误和代码编译。为什么不起作用?谢谢你抽出时间。
读取XML文件的整个循环
//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
// Read next element
QXmlStreamReader::TokenType token = xmlReader->readNext();
//If token is just StartDocument - go to next
if(token == QXmlStreamReader::StartDocument) {
continue;
}
//If token is StartElement - read it
if(token == QXmlStreamReader::StartElement) {
if(xmlReader->name() == "time_delay") {
qWarning() << xmlReader->readElementText(); // OUTPUTS 15
if ( !(imgDur = QString (xmlReader->readElementText()).toDouble() ) ){
qWarning() << "AS AN DOUBLE" << imgDur; // OUTPUTS 0
imgDur = 10;
}
}
if(xmlReader->name() == "value") {
qWarning() << xmlReader->readElementText(); // OUTPUTS 8
}
}
}
代码的主要问题是这一行qWarning() << xmlReader->readElementText(); // OUTPUTS 15
。QXmlReader::readElementText()
将xmlReader指针移动到文本节点的末尾,因此readNext()
将返回A
的EndElement
,而不是QXmlStreamReader::Characters
令牌。因此,readElementText
基本上是这样做的(请注意,在实际实现中,它要复杂得多,因为它检查默认行为,设置QXmlStreamReader内部数据/状态/令牌等):
QString retval;
if(xmlReader->readNext() == QXmlStreamReader::Characters)
{
retval = xmlReader->text().toString();
xmlReader->readNext();
}
return retval;
因此,基本上第二个xmlReader->readElementText();
将始终返回空的QString,因为当前令牌不再是QXmlStreamReader::StartElement
首先,我们假设imgDur是一个浮点值。然后将if语句更改为
QString tempText = xmlReader->readElementText();
if (imgDur != tempText.toDouble()) {
有两个问题,您的条件语句是真值语句,并且您将QString冗余地转换为QString。
您在问题的注释中提到,您试图转换的字符串中包含的数字是15。总是15岁吗?如果是这样,您应该使用QString::toInt
,以及一个整数类型来将该函数的返回值存储在.中
如果它更具动态性,您最好利用toDouble的bool*
参数,并将代码更改为以下内容:
bool ok = false;
imgDur = xmlReader->readElementText().toDouble(&ok);
if (!ok) {
imgDur = xmlReader->readElementText().toInt(&ok);
if (!ok) {
imgDur = 10.0;
}
}