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.