|
|
|
|
|
|
|
Examples (1) and (2) are straightforward examples of integer input. Example (3) shows that you do not use quotes around character data values when they are input (quotes around character constants are needed in a program, though, to distinguish them from identifiers). Example (4) demonstrates how the process of skipping whitespace characters includes going on to the next line of input if necessary. Example (5) shows that the first character encountered that is inappropriate for a numeric data type ends the number. Input for the variable i stops at the input character A, after which the A is stored into ch, and then input for x stops at the end of the input line. Example (6) shows that if you are at the keyboard and haven't entered enough values to satisfy the input statement, the computer waits (and waits and waits ) for more data. Example (7) shows that if more values are entered than there are variables in the input statement, the extra values remain waiting in the input stream until they can be read by the next input statement. If there are extra values left when the program ends, the computer disregards them. |
|
|
|
|
|
|
|
|
The Reading Marker and the Newline Character |
|
|
|
|
|
|
|
|
To help explain stream input in more detail, we introduce the concept of the reading marker. The reading marker works like a bookmark, but, instead of marking a place in a book, it keeps track of the point in the input stream where the computer should continue reading. The reading marker indicates the next character waiting to be read. The extraction operator >> leaves the reading marker on the character following the last piece of data that was input. |
|
|
|
|
|
|
|
|
Each input line has an invisible end-of-line character (the newline character) that tells the computer where one line ends and the next begins. To find the next input value, the >> operator crosses line boundaries (newline characters) if it has to. |
|
|
|
|
|
|
|
|
Where does the newline character come from? What is it? The answer to the first question is easy. When you are working at a keyboard, you generate a newline character yourself each time you hit the Return or Enter key. Your program also generates a newline character when it uses the endl manipulator in an output statement. The endl manipulator outputs a newline, telling the screen cursor to go to the next line. The answer to the second question varies from computer system to computer system. The newline character is a nonprintable control character that the system recognizes as meaning the end of a line, whether it's an input line or an output line. |
|
|
|
|
|
|
|
|
In a C++ program, you can refer directly to the newline character by using the two symbols \n, a backslash and an n with no space between them. Although \n consists of two symbols, it refers to a single characterthe newline character. Just as you can store the letter A into a char variable ch like this: |
|
|
|
|
|