CS 1440 Lab 6

Cover sheetPrevious ActivityNext Activity

Activity 6-4: Getting the spaces

Activity Goals

Understanding how to get input spaces with the cin.get( ) and getline( ) functions.

Activity Procedure

In the previous activity you learned that the stream extraction operator  >>  skips white space and uses white space to separate input values.  Even newlines (Enter keys) are skipped.  But what if we need the spaces?  The istream data type (cin’s data type) provides a special function to get a single character – EVEN WHITE SPACE CHARACTERS.

Copy your getchars.C program into the file getc.C and make the following changes.  Replace each extraction operator with this special function call.

cin >> a;                                needs to become                      cin.get(a);

Note that if you used one cin statement like  cin >> a >> b >> c  that you will now need three statements like above.

Now, compile and run this using the same input data as in the previous activity:

1.      When prompted, key in:            1  2  3

2.      When prompted key in:             123

3.      When prompted, key in:            A  b  C

4.      When prompted key in:             A              11                  C

5.      When prompted key in:             A

6.      When prompted key in:             1.3   2   3.5   

Did you notice how it behaved differently?  To really see the spaces you may wish to modify the output statements in getc.C to “surround” the character like this:

cout  <<  "("  << a  <<  ")"  << endl;

Now the character is surrounded by parenthesis and you can “see” the spaces!


What about spaces in strings?

Yet another good question!  We often want the spaces in our strings, for things like names, titles, etc.  For this there is the getline function.  The getline function requires two parameters, an istream and a string.  It reads from the input stream until a newline is encountered (it does read the newline) and returns the characters read but without the newline.  Copy and paste the following program into a file called gets.C and compile and run it.  Be sure to put spaces in the input string!

#include  <iostream>
#include  <string>
int main() {
     string s;
     cout << "Enter a string (spaces are okay!) :";
     getline(cin, s);
     cout << s << endl;

Activity Followup

Explain why this doesn’t seem to work as intended.  Specifically, the program doesn’t really let us enter the string.  You may find it helpful to copy and paste the following program into a file, compile and run the program. 

#include  <iostream>
#include  <string>
int main() {
     string s;
     int x;
     cout << "Enter an int on one line and a word on the next line :";
     cin >> x;
     getline(cin, s);
     cout << x << endl;
     cout << s << endl;   // Why does this print a blank line?