Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: expected unqualified-id before 'if'

I've googled this error until I'm blue in the face, but haven't been able to relate any of the results to my code. This error seems to be caused, usually, but misplaced or missing braces, parents, etc.

It's also been a long time since I wrote any C++, so there could be some obvious, foolish thing that I'm missing.

This is a Qt Mobile app that I'm writing in Qt Creator 2.4.0, Based on Qt 4.7.4 (64 bit) Built on Dec 20 2011 at 11:14:33.

#include <QFile>
#include <QString>
#include <QTextStream>
#include <QIODevice>
#include <QStringList>

QFile file("words.txt");
QStringList words;

if( file.open( QIODevice::ReadOnly ) )
{
    QTextStream t( &file );

    while( !t.eof() ) {
        words << t.readline();
    }

    file.close();
}

What am I missing? Thanks in advance.

like image 368
mwcz Avatar asked Dec 31 '11 20:12

mwcz


People also ask

What does expected unqualified ID before mean?

The expected unqualified id error shows up due to mistakes in the syntax. As there can be various situations for syntax errors, you'll need to carefully check your code to correct them. Also, this post points toward some common mistakes that lead to the same error.

What does unqualified ID mean in C++?

A qualified name is one that has some sort of indication of where it belongs, e.g. a class specification, namespace specification, etc. An unqualified name is one that isn't qualified.

What is expected unqualified ID before numeric constant?

expected unqualified-id before numeric constant Cython is a tool to wrap C/C++ code so that it can interface with a Python interpreter. Cython generates the wrapping code and sends it to GCC.


1 Answers

You can't have free-standing code like that. All code needs to go into functions.

Wrap all that in a main function and you should be ok once you've fixed your use of QTextStream (it has no eof method, and it doesn't have a readline method either - please look at the API docs that come with usage examples).

#include <QFile>
#include <QString>
#include <QTextStream>
#include <QIODevice>
#include <QStringList>

int main()
{
  QFile file("words.txt");
  QStringList words;

  if( file.open( QIODevice::ReadOnly ) )
  {
    QTextStream t( &file );

    QString line = t.readLine();
    while (!line.isNull()) {
        words << line;
        line = t.readLine();
    }

    file.close();
  }
}
like image 119
Mat Avatar answered Oct 07 '22 16:10

Mat