代码中的解析错误:令牌之前的预期' ; ' ' { ' - 是什么原因造成的?

Parse error in code: expected ' ; ' before ' { ' token -- what is causing this?

本文关键字:是什么 错误 令牌 代码      更新时间:2023-10-16

我得到的错误是error: expected ' ; ' before ' { ' token

我尝试通过在if (thisisanumber==5)else (thisisanumber!=5)之后添加;来修复代码。虽然这解决了第一个错误,但它创建了另一个错误,即error: ' else ' without a previous ' if '。我真的很想知道我在写代码时犯了什么错误,谢谢。

这是我的代码:

#include <iostream>
using namespace std;
int main()
{
    int thisisanumber;
    cout<<"Whats the Password?: ";
    cin>> thisisanumber;
    cin.ignore();
    if (thisisanumber==5) {
        cout<<"You've discovered the password! Wow, you're a genious you should be proud./n";
        }
    else (thisisanumber!=5) {
        cout<<"You've failed in knowing the password and therefore cannot enter, leave and do not come back. Goodbye!/n";
        }
    cin.get();
}

您缺少关键字if:

else if (thisisanumber!=5) {
     ^^

或者,由于与thisisanumber == 5相反的条件是thisisanumber而不是5,因此不需要条件:

else {

您不需要其他条件,因为只有两种情况-只需使用else { ... },它就会捕获thisisanumber==5false的所有情况。

if语句的结构是:

if (condition) { ... }
else if (another condition) { ... }
// ... more conditions
else { ... all cases in which no previous condition matched end up here  ... } 

但CCD_ 13和CCD_。

编译器会查看以下内容:

else (thisisanumber!=5) {

并自言自语:

"好吧,这是else。下一个令牌是if吗?不是。好吧,所以这是一个else子句,接下来的事情是在else情况下该怎么办。下一令牌是{吗?不是。好的,那么在其他情况下,我们执行一条语句,而不是一个块。下一个令牌是(吗?对好的,所以我们的语句用括号括起来。。。[插入此处:解释用括号括起来的表达式的其余思维过程]好吧,这是匹配的)。Whew。现在让我们为这个语句匹配;。。。等等,这是什么?{!这是不对的。"

编译器从左到右一次读取一个标记的代码。它不会在人类理解的逻辑意义上报告错误。它报告的错误是,通过从左到右一次读取一个令牌的代码,它首先能够检测到错误。

else (thisisanumber!=5);是合法的。这意味着"如果该数字不等于5(因为if测试失败),则检查该数字是否不等于5,并且不处理该比较的结果"。毫无意义,但合法。写else if (thisisanumber!=5) {...}也是合法的,这大概就是你的意思。这意味着"如果这个数字不等于5(因为if测试失败),而且这个数字也不等于5,那么就在{}中做这些事情"。但这是多余的:给定某个不等于5的值,它就保证不等于5,所以指定两次测试没有意义。所以我们应该只写else {...}

"else"实际上是"otherwise"的缩写,在C++中也有这个目的。