错误:'if' 之前的预期不合格 ID [英] error: expected unqualified-id before 'if'

查看:49
本文介绍了错误:'if' 之前的预期不合格 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我也有很长时间没有写过任何 C++,所以我可能遗漏了一些明显的、愚蠢的东西.

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

这是我在 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();
}

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

What am I missing? Thanks in advance.

推荐答案

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

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

将所有内容包装在 main 函数中,一旦您修复了 QTextStream 的使用,您应该就可以了(它没有 eof方法,它也没有 readline 方法 - 请查看 API 文档 附带使用示例).

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

这篇关于错误:'if' 之前的预期不合格 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆