Writing a program to print a "Hello, world!" program

10,903

Solution 1

You're not actually calling your helloWorld function anywhere. How about:

int main()
{
    helloWorld(); // Call function

    cin.get();
    return 0;
}

Note: You'll also need to declare your function prototype at the top if you want to use it before it's defined.

void helloWorld(void);

Here's a working sample.

Solution 2

The way I read the textbook exercise is that it wants you to write a program which prints out another C++ program to the screen. For now, you need to do this with a lot of cout statements and literal strings surrounded by ""s. For example, you can start with

cout << "#include <iostream>" << std::endl;

Solution 3

To call a function, you need to:

  • Provide a declaration prior to its use
  • Follow its name with a pair of parantheses, even if it doesn't have any arguments.
  • Provide a return value in order to use it in an expression.

For example:

std::string helloWorld();

int main()
{
   cout << helloWorld() << endl;
   ...
}

std::string helloWorld()
{
    return "Hello, world!";
}
Share:
10,903
iKyriaki
Author by

iKyriaki

Updated on June 15, 2022

Comments

  • iKyriaki
    iKyriaki almost 2 years

    I just started reading Accelerated C++ and I'm trying to work through the exercises when I came across this one:

    0-4. Write a program that, when run, writes the Hello, world! program as its output.

    And so I came up with this code:

    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        cout << helloWorld << endl;
    
        cin.get();
        return 0;
    }
    
    void helloWorld(void)
    {
        cout << "Hello, world!" << endl;
    }
    

    I keep getting the error 'helloWorld' : undeclared identifier. What I figured I was supposed to do is make a function for helloWorld then call that function for the output, but apparently that's not what I needed. I also tried putting helloWorld() in main, but that didn't help either. Any help is greatly appreciated.