Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
https://youtu.be/_mIr6oA8D_k C++ Input Stream

Input Stream


Video Summary: https://youtu.be/_mIr6oA8D_k


There are two ways to get input into our programs. First, we use istream variable cin together with the extraction operator >> to get data from the standard input device — the keyboard. The other way is to get data from a file to the program. We will talk about that next lab.

Here is the syntax template for an input statement

cin >> Variable >> Variable ...;

When you enter data at the keyboard, you must be sure that each value is appropriate for the data type of the variable in the input statement. If nothing can be read for a variable then input will fail and, unless you take special action, nothing more can be read by your program. This will cause unexpected behaviour.

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 '\n'). 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 or letter. If the data value is a char value, one printable character is input.

 

.get()

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.

Whether you use .get() or >>, when input is finished for one variable, input continues to the next one until all input requests are satisfied. If there is not enough input, the program will wait for the user to type more and press enter. If there is too much input it will be remembered until the next time input is needed and then it will be used.

Now look at the following character reading example. Compile and run the two tests with the same set of the input data. e.g.

a b c d

or

a
b
c
d

Examine the results carefully.


Mixing Types

This next program demonstrates reading mixed datatypes with one cin.Try the mixed type test with this input:

3.1416Huh? What's going on?



getline()

In the example above, did you notice the neat trick to get more than one word into a string? 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.