Folder101   Home Notes Quiz Assigns Info  
Forum Forum
101 Home 101
 
  C++ Level 2

Hello Again - Your Second Program

Introduction

Getting Started

Streams

cin function

cout function

Special Escape Characters

Extension Work


  Introduction

Lets create another program that receives input from the command console as well as sending output. For this we will be looking at the cin and the cout functions. We will also be covering special escape characters.


  Getting Started

Step 1- Create a New Project

Open a new project in VC++. You may follow the instructions in the first Hello World! tutorial again if you have forgotten how to do this. Name your project something like HelloAgain. Ensure you have added a source code file in your project. You can save that as HelloAgainSource.cpp if you like.

Step 2- Type in the code

Copy the code shown below into your program. Be careful with syntax errors.

 
#include <iostream.h>
int main()
{
char name[20];
int age;
cout << "Hello Again!\n" << "Please enter your first name.\n";
cin >> name;
cout << "How old are you?\n";
cin >> age;
cout << "Hello " << name << ". You are " << age << " years old." << endl;
return 0;
}

Step 3 - Compile, Link and Run

Select Build from the menu or use the toolbar Build button. This will compile and link your code provided there are no errors. If there are any error messages from the compiler then fix them.

Select Execute from the Build menu or click on the toolbar button

Now that you have tried out your new program, lets examine the code in more detail by starting with the concept of streams.


  Streams

A library is a collection of compiled .obj files that can be linked to your program. The standard C++ library includes the iostream library, which controls input and output (I/O).

You can think of a stream as data being poured byte by byte into a buffer, which then gets sent to the standard input or output (the screen or disk.) It is better for data to be buffered first. Imagine you have to carry a pile of books from one room to another. It would be easier to put them in a box (the buffer) than carry them one by one - don't you think. It is the same principle with a data stream. The stream buffer fills with data until it is full and then the data gets sent where it has to go.

Two of the iostream classes you have used already are...

  • cin
  • cout

Both of these functions use buffers and stream data. Lets look at them in more detail.


  cin Function

cin handles input from the standard input, the keyboard. I.e.

cin >> age;

The extraction operator >> is used to redirect data from the cin buffer to a variable. In this case, the variable that will hold the data is called age. In other words, when I type a number in, it will be stored in the age variable. cin is quite clever because it can figure out what type of variable it is writing data to. In the example above, the data is being written to an integer variable.

Here is cin writing data to a character array:-

cin >> name;

A character array is just a set of characters. You will learn more about character arrays later, but it is important to note that cin writes an extra special character at the end of the set. This special character is the \0 null character combination, which denotes the end of a string. In other words, if the characters... a n g e l a ...are typed in, cin will fill the character array with... a n g e l a \0.

You should always ensure you have enough room in a character array to allow for the entire string plus the null \0. I declared the name array as char name[20], which is enough room for 19 characters plus 1 for \0.

One problem with cin though is to do with whitespaces. Try entering both your first and second name into your program HelloAgain when prompted for your name. What happens? Yes, weirdly, only your first name is accepted. This is because of the whitespace beteen the names. When cin sees a space or a new line, it assumes the input has ended there and ignores any input after the whitespace or newline.

Lets have a closer look at the following lines of code in your program:-

cout << "Hello Again!\n" << "Please enter your first name.\n";
cin >> name;
cout << "How old are you?\n";
cin >> age;
cout << "Hello " << name << ". You are " << age << " years

Look what happens if I use a whitespace with the first cin:-

Because I included a whitespace between 'homer' and 'simpson', cin just took the first word 'homer' and left the word 'simpson' in the keyboard buffer. When cin attampted to get an age input, since 'simpson' was left in the buffer, that was immediately written into the age variable without waiting for any further input from me. Since the age variable expected a number, the word 'simpson' was converted to a strange number.

One way around the whitespace problem is to use:-

  • cin.getline() - reads a specified number of characters from the keyboard buffer into its own buffer. Subsequent characters up to a terminating newline and the newline character are also read and thrown away.
  • cin.ignore() - is also useful. It ignores a specified number of characters until a terminating character is found.

Try inserting the following lines into your code - just before the return 0; line.

 
char address[80];
cout << "Please enter your street address.\n";
cin.getline(address,80);
cout << "Your street address is: " << address;

As you can see, getline allows for whitespaces between text.


  cout Function

cout handles output to the standard output, the screen. The insertion operator << is used to direct data to cout. Looking at your code:-

cout << "Hello Again!\n" << "Please enter your first name.\n";

The words "Hello Again!" are first output to the screen. The \n is an escape character that tells cout to insert a newline at that point. Then the insertion opertator << is again used to write "Please enter your first name" to the screen. Once again, \n is used to insert another newline.

Try removing the escape character \n from the line. Recompile, link and run your program. What do you get? Now put the newline indicators back.

Another way of inserting a newline is to use endln. Moreover, endln will flush the output buffer. This can be convenient when you need to ensure that the output buffer is emptied and that the contents are written to the screen. So, here is another way of achieving similar output:-

cout << "Hello Again!\n"Please enter your first name." << endl;

This time I used \n within a sentence to ensure "Please enter your first name." is put on a line below "Hello Again!". Also, I used endl instead of \n to insert another newline at the end of the output. Try it.

There are other escape characters that can be used with cout. These are listed below.


  Special Escape Characters

The C++ compiler recognizes some special formatting characters. Some of the most commonly used are shown below. You may notice that they all start with the backslash (called the escape character), followed by the character.

\n     new line

\t      tab

\b     backspace

\r     carriage return

\a     alert bell

\"     double quote

\'     single quote

\?     question mark

\\     backslash

You may wonder why escape characters are necessary. Here is one necessity. Say you wanted to output "Lets have "quote marks" in this sentence" to the screen. Try it:-

cout << "Lets have "quote marks" in this sentence";

You would get a compiler error because it thinks there are two separate sentences, "Lets have " and " in this sentence" and it doesn't understand the words between these sentences. This could be fixed by using escape characters. I.e.

cout << "Lets have \"quote marks\" in this sentence";

Then the compiler understands you want to include quote marks in your output.


  Extension Work

Carry out the following exercises:-

  1. In your HelloAgain program, insert the following line just after the int age; line:-

    cout << "Welcome to my program.\a" << endl;

    What is the effect of the \a escape character?

  2. Now insert the following line:-

    cout << "\t\tWelcome to my program.\a" << endl;

    What is the effect of the \t escape character? Try putting another \t in.

  3. Now start step1 and step2 of the practice assignment 3

That it!

Now try the quiz.