Tutorial 2 – Output
I’m going to try to not repeat myself in any of these tutorials so I won’t be talking about any stuff from previous tutorials (but you can always go back and refresh your memory!).
So we’ve got our first application started, but it’s rather boring. Let’s put something a bit more interesting in there.
At the top of your code file add the following:
In C++ you can make your programs use header files by using the #include command. Header files contain declarations of things such as classes, functions, variables types etc. By including the header in your application you will have access to everything named in the header file. In this bit of code you’ve included the stdio header (or standard input/output). This contains various types and functions required to perform IO operations.
In this case we have used the angular brackets <headerFile.h> which means look in the known folders specified by the INCLUDE environment variable. You can also use inverted commas “headerFile.h” which will only look in the current project’s directory.
Now that we have access to some IO stuff, let’s use it! Add the following code in your main function:
printf is a function that’s declared in the stdio header which prints out a formatted string to the standard output (in this case the console window). If you run the program now you’ll see that it does just that, prints out “Hello world”. The ‘\n’ at the end just means finish with a new-line.
printf can also be used to output the value of variables and constants too. for example:
printf("Some number = %d\n", 42);
This means treat the value “42” as an integer (%d means integer) and print it’s value. So this code will print out “Some number = 42” to the console. Try it out!