IO and Namespaces

Output

The keyword cout will output. Use the << operator to output the data following it.

cout << "Output sentence";

Either write std::cout or use the std namespace as follows:

#include <iostream>
using namespace std;
cout << "hello";

For simplicity I will always implicitly include the std namespace

The output can also be chained into a single statement

cout << "This " << " is a " << "single C++ statement";

This is useful when you mix variables and literals together.

int age = 20;
int zipcode = 99999;
cout << "I am " << age << " years old and my zipcode is " << zipcode;

The std::endl or endl manipulator function (there are no arguments) will enter a newline and flush the output stream. The following code appears on two different lines.

cout << "My name is Nissan" << endl;
cout << "How are you doing?" << endl;

Input

The keyword cin or std::cin is for input

The following will enter the input into the variable age when the ENTER key has been pressed. Notice >>

Strings are defined using std::string or string keyword and then variables' name. Don't forget to include string

Putting it all together we get

A little bit more difficult example is the following

valid input

invalid input

Namespaces

Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.

To create a namespace use the namespace keyword. To use the namespace created use the :: operator

output

Namespaces can also be used to access functions

output

To access a namespace without explicitly calling each the the ns::variable you may do the use the using keyword

notice using namespace ns; on line 8. This allows us to use x and value in the namespace without using the :: operator

Note: It's actually best practice not to import the entire namespace into your program because it pollutes your namespace. This can lead to naming collisions. It's best to import only what you are using. So use std::cout instead of cout. A better solution is to use the namespace only where you need it, for example inside the function.

Last updated