简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM