【问题标题】:error: expected unqualified-id before 'while'|错误:'while' 之前的预期不合格 ID|
【发布时间】:2017-03-22 08:01:55
【问题描述】:

在第 12 行继续出现此错误

#include <iostream>

int num = 1;
int number;
int total = 0;
while (num<=5){
    cin >> number;
    total +=number;
    num++;
    cout<< total<<endl
}

【问题讨论】:

  • 看起来您可能缺少包含该代码的函数。
  • 在 C++ 语言中,语句应该写在函数内部。你不能只在文件中间写一个交互语句(你的while)。
  • 只有 11 行,所以第 12 行标志着文件结束。请注意,C++ 语法将可执行语句限制为函数体。
  • 根据定义,C++ 程序需要一个main 函数,因为main 是第一个执行的函数。

标签: c++


【解决方案1】:

您的代码缺少一个int main(void) 函数,您的所有代码都应该在该函数中。根据定义,C++ 程序需要具有int main(void) 函数。您需要将所有代码放入int main(void) 函数中。

此外,您的 cin &lt;&lt;cout &lt;&lt; 语句缺少命名空间标记 std::。因此,您需要在使用cincout 的每个实例中添加std::,请参见下面的代码:

#include <iostream>

int main(void) // The main() function is required in a C++ program
{
    int num = 1;
    int number;
    int total = 0;
    while (num <= 5)
    {
        std::cin >> number; // You need to add the reference to std:: as "cin <<" is a part of the std namespace
        total += number;
        num++;
        std::cout << total << std::endl // You need to add the reference to std:: as "cout <<" and "endl <<" is a part of the std namespace
    }

    return 0;
}

【讨论】:

  • int main(void) 函数不返回值。它会起作用,但它不是 C++ 标准。 en.cppreference.com/w/cpp/language/main_function
  • @SantiagoVarela,这是标准 C++,main(没有别的,只有 main)在到达函数末尾时返回 0。
  • 这与我的评论@chris 有何冲突?我指的是主要功能并引用来源...
  • @SantiagoVarela,你说从main 的末尾掉下来不是标准的 C++。我说的是,你的参考同意:4)main函数的主体不需要包含return语句:如果控制到达main的末尾而没有遇到return语句,效果是执行 return 0;.
  • 我意识到我错过了主要评论,愚蠢的我。现在我在尝试运行代码时遇到了另一个错误。它说 ||=== Build: Debug in First C++ App (编译器:GNU GCC 编译器)===| ||错误:无法创建 obj\Debug\main.o:权限被拒绝| ||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)===|有什么帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多