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

戏子无情 提交于 2021-01-05 12:24:40

问题


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

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.

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(){
           ^

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


回答1:


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

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

int main() {

    return 0;
}

UPDATE

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

  • shortcut
#include <iostream>
using namespace std;

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

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

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

   return 0;
}

Why std::endl is not needed?

Some of the comments are suggesting that changing

cout << result;

to

cout << result << endl;

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).



来源:https://stackoverflow.com/questions/59918809/c-using-g-no-result-no-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!