C++ Input and Output

You can use the cin and cout operators (pronounced C-in and C-out) to get input from the keyboard and output data to the screen. In order to use these operators, you must place the #include <iostream> preprocessor directive bfore your main() function. If you don't really care what the preprocessor is doing, skip the next paragraph.

Before the C++ compiler compiles your source code, it sends your code to the preprocesser. The preprocessor modifies your source code according to the information you supply in the preprocessor directives. Tne #include preprocessor directive tells the preprocessor to merge your source code with a pre-existing file. When we use the #include <iostream.h> preprocessor directive, our code is merged with a file that has the code for the cin and cout operators. The line using namespace std; gives you access to some of the more advanced features of C++.

We can use cout to print a string of characters (called a string)to the screen. In the following program all three strings are printed on one line.



     #include <iostream>
     using namespace std;

     int main()
     {
      cout << "One if by land.";
      cout << "Two if by sea.";
      cout << "Three if by both.";
      cin.get();
      return 0;
     }

The output of the above program will look like this:

One if by land.Two if by sea.Three if by both.

If you want the lines to print on different lines you must use the newline character "\n". Thus the following code prints three separtate lines of text.



     #include <iostream>
     using namespace std;

     int main()
     {
      cout << "\nOne if by land.\nTwo if by sea.\nThree if by both.";
      cin.get();
      return 0;
     }

The output

One if by land.
Two if by sea.
Three if by by both.

To get input from the user we use the cin operator. But first we will need to declare a variable in which to store the input. We declare a variable by chosing the type of variable and then naming the variable. Let's declare a variable of type int and name our varrible "age".



     int age;
We have just declared a variable called "age" that will hold an integer value. Don't forget the semicolon when declaring varibles. (Declaring variables will be covered in more detail in the next section. ) Now we can use our variable to hold user input.


     #include <iostream>
     using namespace std;

     int main()
     {
      int age;
      cout << "\nPlease enter your age in number of years: ";
      cin >> age;
      cout << "\nYou are " << age " years old.\n";
      cin.get():
      cin.get();
      return 0;
     }