Synfire's Guide to C++

2. cout and cin

Here I will talk about the first two keywords you are gonna learn.
cout and cin.

This section is broken down into subsections, one for each keyword. Note that both of these keywords lie in the iostream.h header file.

cout
cout is a reserved keyword that allows you to print to the screen. This can be done by using 'cout << "string" << endl;'. This code prints 'string' on a line by itself. The endl argument tells cout to start on a new line.

example
#include <iostream.h>

int main()
{
    cout << "Hello World" << endl;
    cout << "how" << endl << "are " << "you " << "today" << endl;
    return 0;
}
This outputs:
Hello World
how
are you today?

See how when you place endl after how it automatically starts a new line. This can also be done using '\n' like so:

example
#include <iostream.h>

int main()
{
    cout << "Hello World\n";
    cout << "how \nare you today\n";
    return 0;
}

This program has the same output as above. You should decide how you want to do this, it's all a point of personal preference.

cin
cin allows a program to accept input from the user of the program. This is done by having cin accept information from the keyboard and placing it into a variable, you will learn more about variables in the next chapter. For now, lets just define a variable as a place that you can store information. Here is an example:

#include <iostream.h>

int main()
{
    int myAge;
    cout << "Enter your age: ";
    cin >> myAge;
    cout << "My Age is " << myAge << " also!";
    return 0;
}

The above program prints a message asking for your age, then it waits for you to input the age and press enter. Anything you type at this moment is assigned to myAge. Note that you can't assign string values to a variable, they must be assigned to a character array. The reason for that is that a variable given the value of 'char', discussed in a minute, only holds one character. Also notice that the myAge variable on line 8 is not in parenthesis this is because you want to print the value of myAge, not the literal statement "myAge".

Summary
In this section you have learned how to print output to the screen and take input from the user.

< < < Lesson 1: Basic Structure | Lesson 3: Variable Basics > > >