PDA

View Full Version : Problems with QString::startsWith("--[[")



Mrodrigues
22nd January 2013, 08:15
Hello everybody.

I'm facing a very strange behavior when using the the following method in Qt (Windows 7 64bit, Qt v.4.8.1, VisualStudio 2010 compiler):

bool QString::startsWith ( const QString & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const.
I'm reading a text file (lua script file) and looking for lines where a comment block exist. Comments blocks are defined by "--[[" at the beginning of the line. Individual lines are then stored in a QStringList .
When executing this code I was hoping that the first comparison would return true, instead it returns a false.



{...}
for( int i=0; i<ioSourceCodeLines.size(); i++)
{
const QString currentLine = ioSourceCodeLines.at(0);
if(currentLine.startsWith("--[["))
insideCommentBlock = true; // dont't stop here.
else if(currentLine.startsWith("--"))
insideComment = true; //stops here.
...
}
{...}


I've inspected the memory values and I've noticed that for some reason the content that is saved in memory for currentLine is slighty different:
2d 00 2d 00 5b 00 20 00 5b 00 20 ... and so on. This translates to the following string. "--[ [ " notice how spaces were added.

If the comparison is made this way:



{...}
for( int i=0; i<ioSourceCodeLines.size(); i++)
{
const QString currentLine = ioSourceCodeLines.at(0);
if(currentLine.startsWith("--[ [ "))
insideCommentBlock = true; // stop here.
else if(currentLine.startsWith("--"))
insideComment = true; //stops here.
...
}
{...}


the result of the first comparison is now true. But that is not what its contained in the file. Does someone has an idea of what is going on, or is it a bug?
I'm just looking for an explanation of this behavior or what is my mistake?
Thanks in advance.

Lykurg
22nd January 2013, 08:51
How do you populate ioSourceCodeLines? Are the encodings right when reading the file?
Does

#include <QtCore>

int main(int argc, char *argv[])
{
QTemporaryFile f;
if (!f.open())
qDebug() << "Could not open file";
qDebug() << "File name" << f.fileName();

QFile file(f.fileName());
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "--[[ foo bar";
file.close();

file.open(QIODevice::ReadOnly | QIODevice::Text);
QString str = file.readLine();
qDebug() << str << (str == "--[[ foo bar");

return 0;
} work for you?

Lesiok
22nd January 2013, 08:53
BTW Is the line number 4 should look like this :
const QString currentLine = ioSourceCodeLines.at(i)

Mrodrigues
22nd January 2013, 13:33
Hello thanks for the answer. It seems now everything is beeing done correctly.
I've added the "QIODevice::Text" when opening the file.


...
QFile sourceCodeFile(iFilePath);
if(!sourceCodeFile.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
...

and now there are no extra spaces and also the comparisons are behaving the way they should.
Thanks