PDA

View Full Version : First C++ Program




GoKyu
Feb 13, 2009, 01:11 AM
Hi all, I'm mainly trying to get back some of the basics of C that I learned many years ago, but just for fun, I tried a basic "Hello World" type program in C++ just to see if I could do it.

Turns out it's harder than I expected. I'm using g++ in Terminal.

My first attempt (based on original source code):


#include <iostream>

main ()

{
cout << "Hello World, I'm a C++ Program!\n\n";
}


This gave me a curt error message:


first.cc: In fuction `int main()`:
first.cc:5: error: `cout` was not declared in this scope

Then I tried again, changing only the line:

#include <iostream>

to

#include <iostream.h>

And it gave me a bunch of warnings about deprecated or antiquated header file names.....BUT...the code compiled fine!

So if you're *supposed* to use just <iostream>, why did I get the initial error, and how do I correct that?

Thanks for any help :)



VPrime
Feb 13, 2009, 01:38 AM
Not sure how different the compiler is for mac/Xcode.. But in windows (Visual studio)

You need to tell it that cout is part of the std namepace by typing
std::cout

Or after you include iostream you go
using namespace std;

dannomac
Feb 13, 2009, 10:26 AM
So if you're *supposed* to use just <iostream>, why did I get the initial error, and how do I correct that?

Thanks for any help :)

VPrime is correct. iostream.h is basically just this:

#warning This file is deprecated
#include <iostream>
using std::iostream;
using std::ostream;
using std::istream;
using std::ios;
using std::streambuf;

using std::cout;
using std::cin;
using std::cerr;
using std::clog;

So all it does is allow old non-standards compliant C++ code to work, but what you should do is:
std::cout << "Hello World" << std::endl;