1

I wrote the function that returns the next character from the QTextStream. There is:

QString peek(QTextStream *stream){
    QString __str = '\0';
    stream->seek(stream->pos() + 1);
    __str = stream->read(1);
    stream->seek(stream->pos() - 2);
    stream->flush();
    return  __str;
}

For example, I have a file:

abcde

When I tried to brought into the function result on the screen, output was correctly: 'b'. But when I tried to output the next character and then the first character, like that:

/* Any function to output */(peek(file) + file->read(1));

Output was: "ca" instead "ba".

What's wrong?

Sorry, if it's stupid question and sorry for my bad english :)

  • I am not getting your question, what exactly you want to do. But watching you output expectation, I think you should change your expression `stream->seek(stream->pos() - 2);` to `stream->seek(stream->pos() - 1);`. Explain more if you can. – Suyog Mar 18 '14 at 17:08
  • Stylistic note: This is not C, there's no reason for you to initialize `QString` like you do. It is also [invalid for you to use any names with double underscores](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) - they are reserved to the implementation. – Kuba hasn't forgotten Monica Mar 18 '14 at 17:11

1 Answers1

1

The order of argument evaluation in the expression below is not defined. It doesn't have to be left-to-right, not at all.

peek(file) + file->read(1)

In your case, it so happens that the read was performed first, advancing the position, and subsequently peek got a 'c' instead of a 'b'.

You need to break it down:

QString result = peek(file);
result += file->read(1);
Q_ASSERT(result == "ba");
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313