1

I am new to C++. I downloaded and run Dev-C++ and I write and run F9 this:

#include <iostream>
using namespace std;

int main()
{
   cout << "Hello, world!";
   return 0;
}

But no "Hello, world!" is printed, why?

3 Answers3

4

Many IDE users have this problem. The program runs but it closes before you can see its results on the screen. One portable fix is to add this at the bottom of main before you return:

std::cin.get();

That way it will wait for you to enter some text before it exits.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2
#include <iostream>
using namespace std;

int main()
{
   cout << "Hello, world!";
   getchar();
   return 0;
}

Add getchar() at the end of your program as a simple "pause-method" as consoles seems to close so fast, so you need to "delay" to see your console.

bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
0

The output is printed to a terminal, and you don't have a newline etc.... very unlikely that you will see it, so

  • Add a newline to the output
  • make sure you have time to read the output before the terminal window closes (add a sleep or something)
  • Don't use using namespace as that is a bad practice and will lead to trouble in your programming.

So like;

#include <iostream>
#include <unistd.h>

int main()
{
   std::cout << "Hello, world!" << std::endl;
   sleep(2);
   return 0;
}
Soren
  • 14,402
  • 4
  • 41
  • 67
  • I am taking lessons from my university and they all use using namespace in their examples D: –  Nov 12 '14 at 02:49
  • You can tell them that it is a bad practice which should be discouraged -- write the full name like `std::cout` -- namespaces are there for a reason. – Soren Nov 12 '14 at 02:52
  • but why? they are never gonna let me pass the lesson if I tell 'em lol –  Nov 12 '14 at 02:52
  • Because you eventually will include multiple packages from namespace `xxx` and namespace `yyy` -- and both those namespaces will have a function `open` -- so now you have no clue as to whether you are calling `xxx::open` or `yyy::open` and you will end up in debug hell. – Soren Nov 12 '14 at 02:55
  • See this for why `using namespace` is bad http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Soren Nov 12 '14 at 02:57
  • You're assuming the OP is using a system that provides ``. – Keith Thompson Nov 12 '14 at 18:18