Input Stream

To get data into programs, there are two ways to do it: First, we use istream variable cin together with the extraction operator >> to get data from the standard input device --- keyboard. The other way is to get data from a file to the program. We will talk about that later.

Here is the syntax template for an input statement

cin >> Variable >> Variable ...; 
When you enter input data at the keyboard, you must be sure that each data value is appropriate for the data type of the variable in the input statement.

The >> operator skips any leading white space characters when it is looking for the next input value in the stream. Whitespace characters are blanks and certain nonprintable characters such as the character that marks the end of a line (new line character). After skipping any whitespace characters, >> operator proceeds to extract the desired data value from the input stream. If the data value is int or float, input of the number stops at the first character that is inappropriate for the data type, such as a whitespace character. Watch out! Bad things happen if there is no number for those types to read. If the data value is a char value, one printable character is input.

The get input function works a little differently. It inputs the next character in the stream regardless of what it is, even if it is a whitespace character or new line character. Now look at the following two examples. Compile and run them with the same set of the input data. e.g. (a b c d or a 2bc). Examine the results carefully.


// Program CharRead prompts for and reads four characters 
// from the keyboard and then prints them.         

#include <iostream>
using namespace std;

int main ()
{
    char  char1;
    char  char2;
    char  char3;
    char  char4;

    cout  << "Input four characters.  Press Return."  << endl;
    cin  >> char1  >> char2  >> char3  >> char4;
    cout  << char1  << char2  << char3  << char4;
    return 0;
}


// Program Char2Rd prompts for and reads four characters 
// from the keyboard and then prints them.            *)

#include <iostream>
using namespace std;

int main ()
{
    char  char1;
    char  char2;
    char  char3;
    char  char4;

    cout  << "Input four characters.  Press Return."  << endl;
    cin.get(char1);
    cin.get(char2);
    cin.get(char3);
    cin.get(char4);
    cout  << char1  << char2  << char3  << char4;
    return 0;
}

Now the last thing to emphasize. For a string variable, say inputStr, the statement

cin >> inputStr;
skips leading whitespace and it stops as soon as it encounters a whitespace character. The statement
getline(cin, inputStr);
does not skip the leading whitespace character(s). It stops when a new line character '\n' is encountered.
getline is a function from C++ standard library.


Copyright: Department of Computer Science, University of Regina.