- Without using cin
#include <iostream.h> void main() { int x, y, sum; x=10; y=20; sum=x+y; cout << "The sum is " << sum; }
- Using cin
#include <iostream.h> void main() { int x, y, sum; cout << "Give the first number "; cin >> x; cout << "Give the second number "; cin >> y; sum=x+y; cout << "The sum is " << sum; }
- Data must be kept separate until the program is executed
- In this way, programs can be used with many different sets of data
<Figure 4-1, page 132>
- Think of it as an endless sequence of characters going to an output device
- cout is predefined is C++ to denote an output stream
- The standard output device is your computer's screen
- Think of it as an endless sequence of characters coming into your program from an input device
- cin is predefined is C++ to denote an input stream
- The standard input device is your computer's keyboard
- Declarations contained in iostream.h for cout and cin
istream cin; (cin is a variable of type istream)
ostream cout; (cout is a variable of type ostream)
|
- The << (insertion) operator means "put data to the output stream"
|
- The >> (extraction) operator means "get data from the input stream"
- The >> operator can be used several times in a single input statement
cin >> x >> y; is equivalent to the following two statements
cin >> x;
cin >> y;
- Important: the items specified in an input statement can only be variable names
- Input data must be appropriate for the data type of the variables in the cin
statement
int i;
char c;
float f;
cin >> f; (if you type in an integer, it will be converted to a float)
cin >> i; (if you type in a float, error might occur !!)
cin >> c; (if you type in an integer or a float, error might occur !!)
- Data entered by a user goes to the input stream and stays there until it is extracted by a cin statement
- Every time the user hits Return or Enter, an invisible character (newline character) is inserted in the input stream
- We refer to the newline character using the symbols \n
* cout << "Hello\n"; is the same as cout << "Hello" << endl;
* endl basically sends a \n character to the output stream
- A newline character lets the computer know that the next data will be provided at the next line
- Usually, users separate the input data with spaces
- Any leading whitespace characters (i.e., blanks or spaces) are skipped
- Depending on the data type of the variable in the cin statement, one or more characters are extracted
* If the variable is of type char, one character is extracted at a time
* If the variable is of type int or float, it keeps extracting
characters from the input stream until a character which is inappropriate for the data
type of the variable is found (e.g., a whitespace)
<Table from page 135>
- Question: How does cin remember which character was extracted last ??
- Answer: It uses a reading marker to indicate the next character waiting to be read !!
<Table from page 137>