13.4 Stream Input

Formatted and unformatted input capabilities are provided by istream. The stream extraction operator (>>) normally skips white-space characters (such as blanks, tabs and newlines) in the input stream; later we’ll see how to change this behavior.

Using the Result of a Stream Extraction as a Condition

After each input, the stream extraction operator returns a reference to the stream object that received the extraction message (e.g., cin in the expression cin >> grade). If that reference is used as a condition (e.g., in a while statement’s loop-continuation condition), the stream’s overloaded bool cast operator function (added in C++11) is implicitly invoked to convert the reference into true or false value, based on the success or failure, respectively, of the last input operation. When an attempt is made to read past the end of a stream, the stream’s overloaded bool cast operator returns false to indicate end-of-file. We used this capability in line 24 of Fig. 5.11.

13.4.1 get and getline Member Functions

The get member function with no arguments inputs one character from the designated stream (including white-space characters and other nongraphic characters, such as the key sequence that represents end-of-file) and returns it as the value of the function call. This version of get returns EOF when end-of-file is encountered on the stream. EOF normally has the value –1 and is defined in a header that’s indirectly included in your code via stream library headers like <iostream>.

Using Member Functions eof, get and put

Figure 13.2 demonstrates member functions eof and get on input stream cin and member function put on output stream cout. This program uses get to read characters into the int variable character, so that we can test each character entered to see if it’s EOF We use int because on many platforms char can represent only nonnegative values and EOF is typically -1. The program first prints the value of cin.eof()—i.e., false (0 on the output)—to show that end-of-file has not occurred on cin. The user enters a line of text and presses Enter followed by end-of-file (<Ctrl> z on Microsoft Windows systems, <Ctrl> d on Linux and Mac systems). Line 14 reads each character, which line 15 outputs to cout using member function put. When end-of-file is encountered, the while statement ends, and line 20 displays the value of cin.eof(), which is now true (1 on the output), to show that end-of-file has been set on cin. This program uses the version of istream member function get that takes no arguments and returns the character being input (line 14). Function eof returns true only after the program attempts to read past the last character in the stream.

Fig. 13.2 get, put and eof member functions.

Alternate View

 1   // Fig. 13.2: Fig13_02.cpp
 2   // get, put and eof member functions.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      int character; // use int, because char cannot represent EOF
 8
 9      // prompt user to enter line of text
10      cout << "Before input, cin.eof() is " << cin.eof()
11         << "
Enter a sentence followed by Enter and end-of-file:
";
12
13      // use get to read each character; use put to display it
14      while ((character = cin.get()) != EOF) {
15         cout.put(character);
16      }
17
18      // display end-of-file character
19      cout << "
EOF in this system is: " << character
20         << "
After input of EOF, cin.eof() is " << cin.eof() << endl;
21   }

Before input, cin.eof() is 0
Enter a sentence followed by end-of-file:
Testing the get and put member functions
Testing the get and put member functions
^Z

EOF in this system is: -1
After input of EOF, cin.eof() is 1

The get member function with a character-reference argument inputs the next character from the input stream (even if this is a white-space character) and stores it in the character argument. This version of get returns a reference to the istream object for which the get member function is being invoked.

A third version of get takes three arguments—a built-in array of chars, a size limit and a delimiter (with default value ' '). This version reads characters from the input stream. It either reads one fewer than the specified maximum number of characters and terminates or terminates as soon as the delimiter is read. A null character is inserted to terminate the input string in the character array used as a buffer by the program. The delimiter is not placed in the character array but does remain in the input stream (the delimiter will be the next character read). Thus, the result of a second consecutive get is an empty line, unless the delimiter character is removed from the input stream (possibly with cin.ignore()).

Comparing cin and cin.get

Figure 13.3 compares input using the stream extraction operator with cin (which reads characters until a white-space character is encountered) and input using cin.get. The call to cin.get (line 20) does not specify a delimiter, so the default ' ' character is used.

Fig. 13.3 Contrasting input of a string via cin and cin.get.

Alternate View

 1   // Fig. 13.3: Fig13_03.cpp
 2   // Contrasting input of a string via cin and cin.get.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      // create two char arrays, each with 80 elements
 8      const int SIZE{80};
 9      char buffer1[SIZE];
10      char buffer2[SIZE];
11
12      // use cin to input characters into buffer1
13      cout << "Enter a sentence:
";
14      cin >> buffer1;
15
16      // display buffer1 contents
17      cout << "
The string read with cin was:
" << buffer1 << "

";
18
19      // use cin.get to input characters into buffer2
20      cin.get(buffer2, SIZE);                        
21
22      // display buffer2 contents
23      cout << "The string read with cin.get was:
" << buffer2 << endl;
24   }

Enter a sentence:
Contrasting string input with cin and cin.get

The string read with cin was:
Contrasting

The string read with cin.get was:
 string input with cin and cin.get

Using Member Function getline

Member function getline operates similarly to the third version of the get member function and inserts a null character after the line in the built-in array of chars. The getline function removes the delimiter from the stream (i.e., reads the character and discards it), but does not store it in the character array. The program of Fig. 13.4 demonstrates the use of the getline member function to input a line of text (line 12).

Fig. 13.4 Inputting characters using cin member function getline.

Alternate View

 1   // Fig. 13.4: Fig13_04.cpp
 2   // Inputting characters using cin member function getline.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      const int SIZE{80};
 8      char buffer[SIZE]; // create array of 80 characters
 9
10      // input characters in buffer via cin function getline
11      cout << "Enter a sentence:
";
12      cin.getline(buffer, SIZE);
13
14      // display buffer contents
15      cout << "
The sentence entered is:
" << buffer << endl;
16   }

Enter a sentence:
Using the getline member function

The sentence entered is:
Using the getline member function

13.4.2 istream Member Functions peek, putback and ignore

The istream member function ignore (which you first used in Section 10.5) reads and discards characters. It receives two arguments:

  • a designated number of characters—the default argument value is 1—and

  • a delimiter at which to stop ignoring characters—the default delimiter is EOF.

The function discards the specified number of characters, or fewer characters if the delimiter is encountered in the input stream.

The putback member function places the previous character obtained by a get from an input stream back into that stream. This function is useful for applications that scan an input stream looking for a field beginning with a specific character. When that character is input, the application returns the character to the stream, so the character can be included in the input data.

The peek member function returns the next character from an input stream but does not remove the character from the stream.

13.4.3 Type-Safe I/O

C++ offers type-safe I/O. The << and >> operators are overloaded to accept data items of specific types. If unexpected data is processed, various error bits are set, which the user may query to determine whether an I/O operation succeeded or failed. If operators << and >> have not been overloaded for a user-defined type and you attempt to use those operators to input into or output the contents of an object of that user-defined type, the compiler reports an error. This enables the program to “stay in control.” We discuss this more in Section 13.8.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset