使用g ++的C ++,无结果,无打印 [英] C++ using g++, no result, no print

查看:62
本文介绍了使用g ++的C ++,无结果,无打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从使用Python逐渐过渡到使用C ++,但我不知道如何运行任何代码.我正在使用g ++编译器,但是我的函数没有任何结果.

I'm slowly moving from using Python to using C++ and I don't understand how to run any code. I'm using the g++ compiler, but I get no results from my functions.

// 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;
}

如果我在VSCode中运行此示例并指定我想使用g ++编译器,它将返回:终端将被任务重用,请按任意键将其关闭..如果我通过cmd对其进行编译并运行任务,则新的cmd窗口将闪烁,并且没有任何反应.

If I run this example inside VSCode and specify that I want to use g++ compiler it comes back with: Terminal will be reused by tasks, press any key to close it.. If I compile it through cmd and run the task, a new cmd window flashes and nothing is happening.

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

I found the g++ doc which says how to compile with g++ and it shows the following example:

#include <stdio.h>

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

但是我什至不能运行编译器,因为它说

But I can't even run the compiler because it says

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

如何在cmd或ide终端中打印内容?我不明白.

How can I print something in cmd or the ide terminal? I don't understand.

推荐答案

我认为您使用的是错误的VSCode.您必须知道默认情况下它没有集成的编译器,但是您需要在命令行中编译源文件并运行可执行文件:

I believe you are using VSCode in a wrong way. You must know that it does not have integrated compiler by default but you need to compile source file in command line and run the executable:

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

您的第一个示例运行没有问题.在此处

Your first example runs with no problem. Check here

您的第二个示例有一个错误,因为C ++中没有 void main().相反,您需要拥有

Your second example has an error because there is no void main() in C++. Instead, you need to have

int main() {

    return 0;
}

更新

如果运行可执行文件导致打开和关闭窗口,则可以使用以下方法之一来解决该问题:

If running the executable results in opening and closing the window you can fix that by using one of the following:

  • 快捷方式
#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 ).

    will fix the issue but, in this case, when the above line is the last line in the main function it really does not matter since program's exit flushes all the buffers currently in use (in this case std::cout).

    这篇关于使用g ++的C ++,无结果,无打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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