First C++ Program

Discussion in 'Mac Programming' started by GoKyu, Feb 12, 2009.

  1. macrumors 65816

    GoKyu

    Joined:
    Feb 15, 2007
    Location:
    New Orleans
    #1
    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):

    Code:
    #include <iostream>
    
    main ()
    
    {
         cout  << "Hello World, I'm a C++ Program!\n\n";
    }
    
    This gave me a curt error message:

    Code:
    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 :)
     
  2. macrumors 68000

    VPrime

    Joined:
    Dec 19, 2008
    Location:
    London Ontario
    #2
    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;
     
  3. macrumors member

    Joined:
    Mar 11, 2008
    Location:
    Saskatoon, SK
    #3
    VPrime is correct. iostream.h is basically just this:

    Code:
    #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:
    Code:
    std::cout << "Hello World" << std::endl;
     

Share This Page