0

I just begin to learn C++, for the main method i do:

#include <iostream>
using namespace std;

int main ()
{
   int d;
   int n;
   cout <<"Enter the denominator: " << endl;
   cin >> d;
   cout <<"Enter the numerator: " << endl;
   cin >> n;
   cout <<"The result of operation is: " << endl;
   cout << (double)n/d << endl;
   cout <<"Done";
   return 0;
}

It doesn't produce output, but if I delete return 0. I will generate correct output. Shouldn't the main method in C++ always return an integer eventually?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
14K
  • 399
  • 1
  • 3
  • 15
  • The function `main` is a special case, as there (and only there) doesn't have to be a `return` statement even though the function returns an `int`. If there's no explicit `return` statement, `0` is returned. [basic.start.main]/5 – dyp May 14 '13 at 01:57
  • See [this question](http://stackoverflow.com/q/636829/335858) for a discussion of what `main()` is supposed to return. – Sergey Kalinichenko May 14 '13 at 01:59
  • 2
    -1 for the meaningless title. – Adrian Shum May 14 '13 at 02:00
  • 1
    Perhaps the window closes right away after printing out the result? – Shomz May 14 '13 at 02:00
  • Your code [works perfectly fine](http://ideone.com/lLnsbs) with `return 0` present. – Sergey Kalinichenko May 14 '13 at 02:00
  • 3
    What exactly do you mean by "doesn't produce output"? You don't even see the first two prompts? You don't see the "Done."? Or what exactly? A `main()` that "executes" to the closing `}` will implicitly perform a `return 0;`. So there should be exactly no difference whether or not you have the `return 0;` as posted in the question. – Michael Burr May 14 '13 at 02:14
  • No doubt running a console program and it closes right away. Try asking for a keypress using something like cin.get() – Aleks May 14 '13 at 07:23

2 Answers2

1

Try cout.flush(); before return. It forces the buffered data to be send to the output.

Number47
  • 493
  • 4
  • 14
0

I went through your code and everything seems to be right. When I run it, it works fine. If you haven't solved it yet try to cut and past your code into a new project. I know that it sounds stupid but it should work.

I hope this will help you.

Petar
  • 56
  • 3