C++ 使用 g++,没有结果,没有打印

C++ using g++, no result, no print

我正在慢慢地从使用 Python 转向使用 C++,但我不明白如何 运行 任何代码。我正在使用 g++ 编译器,但我的函数没有得到任何结果。

// arrays example
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
  for ( n=0 ; n<5 ; ++n )
  {
    result += foo[n];
  }
  cout << result;
  return 0;
}

如果我 运行 此示例插入 ide VSCode 并指定我想使用 g++ 编译器,它会返回:Terminal will be reused by tasks, press any key to close it.。如果我通过 cmd 和 运行 任务编译它,一个新的 cmd window 会闪烁并且什么也没有发生。

我找到了 g++ 文档,其中说明了如何使用 g++ 进行编译,并显示了以下示例:

#include <stdio.h>

void main (){
    printf("Hello World\n");
}

但我什至无法 运行 编译器,因为它说

error: '::main' must return 'int'
 void main(){
           ^

如何在 cmd 或 ide 终端中打印内容?没看懂。

我认为您使用 VSCode 的方式有误。你必须知道它默认没有集成编译器但是你需要在命令行中编译源文件和运行可执行文件:

$ g++ hello.cpp
$ ./a.out

您的第一个示例 运行 没问题。检查 here

你的第二个例子有一个错误,因为在 C++ 中没有 void main()。相反,您需要

int main() {

    return 0;
}

更新

如果 运行ning 可执行文件导致打开和关闭 window 您可以使用以下方法之一解决该问题:

  • 快捷方式
#include <iostream>
using namespace std;

int main() {
   system("pause");

   return 0;
}
  • 首选
#include <iostream>
using namespace std;

int main() {
   do {
     cout << '\n' << "Press the Enter key to continue.";
   } while (cin.get() != '\n');

   return 0;
}

为什么不需要std::endl?

一些评论建议改变

cout << result;

cout << result << endl;

会解决这个问题,但是,在这种情况下,当上面一行是 main 函数的最后一行时,这真的无关紧要,因为程序退出会刷新当前使用的所有缓冲区(在这种情况下 std::cout).