Sams Teach Yourself C++ in 21 Days

(singke) #1

Using cin.ignore()......................................................................................


At times, you want to ignore the remaining characters on a line until you hit either end of
line (EOL) or end of file (EOF). The member function ignore()serves this purpose.
ignore()takes two parameters: the maximum number of characters to ignore and the
termination character. If you write ignore(80,’\n’), up to 80 characters will be thrown
away until a newline character is found. The newline is then thrown away and the
ignore()statement ends. Listing 17.8 illustrates the use of ignore().

LISTING17.8 Using ignore()
0: // Listing 17.8 - Using ignore()
1: #include <iostream>
2: using namespace std;
3:
4: int main()
5: {
6: char stringOne[255];
7: char stringTwo[255];
8:
9: cout << “Enter string one:”;
10: cin.get(stringOne,255);
11: cout << “String one: “ << stringOne << endl;
12:
13: cout << “Enter string two: “;
14: cin.getline(stringTwo,255);
15: cout << “String two: “ << stringTwo << endl;
16:

610 Day 17


get()and getline()
The member function get()is overloaded. In one version, it takes no parameters and
returns the value of the character it receives. In the second version, it takes a single char-
acter reference and returns the istreamobject by reference.
In the third and final version, get()takes a character array, a number of characters to
get, and a termination character (which defaults to newline). This version of get()reads
characters into the array until it gets to one fewer than its maximum number of charac-
ters or it encounters the termination character, whichever comes first. If get()encounters
the termination character, it leaves that character in the input buffer and stops reading
characters.
The member function getline()also takes three parameters: the buffer to fill, one more
than the maximum number of characters to get, and the termination character. get-
line()functions the same as get()does with these parameters, except getline()throws
away the terminating character.
Free download pdf