C++ Tutorial for noobs - Part 2: Output
...Back to Part 1: Installation
Cout
Before we can learn the cool stuff, we first have to find a way to test our code.
Here is how our program looks after installing C++ and creating a new project:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
There is a function that allows us to throw things towards the user, this function is called cout. The function is located in another C++ source code file. In order to use cout, we will have to include the other source code file (iostream) and then use it like this:
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::cout<<"Hello World!";
return 0;
}
Note: std::cout means 'use the cout function from the std library'.
If we run the program, we can see "Hello World" in the console window.
Keeping the Console alive
Depending on which C++ IDE we use, the console window might just pop up and close itself again afterwards.
To avoid it, we can use the cin.get() function like this:
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::cout<<"Hello World!";
std::cin.get(); // keep alive
return 0;
}
Linebreaks
If we want to give out more than one message, we just have to add the line-break character '\n' at the end of each message:
std::cout<<"Line 1\n";
std::cout<<"Line 2\n";
std::cout<<"Line 3\n";
Giving out different Types
Cout pretty much works with all kinds of data-types, hence it doesn't care if we want to give out text like "Hello World", or numbers like 42 or a combination of both.
All we have to do is put << between each thing that we want to give out:
std::cout<<"Test: "<<42;
Summary
This was the rather short output tutorial. Whenever we want to test some code from the next parts, we simply include iostream and put std::cout in front of whatever we want to test.