C++ 错误:'if' 之前的预期不合格 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8690446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: expected unqualified-id before 'if'
提问by mwcz
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.
我也已经很久没有写过任何 C++ 了,所以我可能遗漏了一些明显的、愚蠢的东西。
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
.
这是我正在编写的 Qt Mobile 应用程序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.
我错过了什么?提前致谢。
回答by Mat
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 docsthat come with usage examples).
将所有这些都包装在一个main
函数中,一旦你确定了你的使用,你应该QTextStream
没问题(它没有eof
方法,也没有readline
方法 - 请查看使用示例附带的API 文档)。
#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();
}
}