c++ - 错误 : expected unqualified-id before 'if'

标签 c++ qt qt4 qt-creator

我用谷歌搜索了这个错误,直到脸色发青,但无法将任何结果与我的代码相关联。这个错误似乎通常是由错位或缺少大括号、 parent 等引起的。

自从我编写任何 C++ 以来也已经很长时间了,所以我可能遗漏了一些明显的、愚蠢的事情。

这是我在 Qt Creator 2.4.0 中编写的 Qt Mobile 应用程序,基于 Qt 4.7.4(64 位)构建于 2011 年 12 月 20 日 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();
}

我错过了什么?提前致谢。

最佳答案

你不能拥有那样的独立代码。所有代码都需要进入函数。

将所有这些都包装在 main 函数中,一旦您修复了 QTextStream 的使用,您应该没问题(它没有 eof方法,它也没有 readline 方法 - 请查看使用示例附带的 API docs

#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();
  }
}

关于c++ - 错误 : expected unqualified-id before 'if' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8690446/

相关文章:

c++ - 如何分配内存对齐的 C++ 对象数组?

c++ - 对相互依赖的对象的 C++ vector 进行排序的简短解决方案?

qt - QImage/QPixmap 大小限制?

c++ - 是否有有关在 Visual Studio 2008 中进行 C++ 编程的教程?

c++ - 如何修复错误 invalid inirection 和 lvalue

c++ - 未显示继承类

c++ - 有没有办法检查 Qt 中的重复连接?

qt - PyQt5翻译: is it possible to run pylupdate5 from Python?

c++ - Qt4中宏的继承

c++ - 将准备好的语句与 sqlite 事务语句一起使用