1: //whitespace_ignore.cpp
2: //Illustrates more C++ input, this time including cin.get() to read
3: //whitespace and cin.ignore() to skip over "unwanted" input.
5: #include <iostream>
6: using namespace std;
8: int main()
9: {
10: cout << "\nThis program is a further lesson on input, illustrating "
11: "both how to read\nwhitespace, and how to skip over (ignore) "
12: "unwanted values in the input\nstream. Read the instructions "
13: "for input carefully, enter values carefully\naccording to those "
14: "instructions, and then study both the resulting output\nand the "
15: "source code equally carefully to reconcile them with the given "
16: "input.\n\nHere are the input instructions:\n"
17: "1. Enter any amount of whitespace, followed by an integer.\n"
18: "2. Enter anything you like on the rest of the line, "
19: "then press Enter.\n"
20: "3. Enter any amount of whitespace, followed by an integer.\n"
21: "4. Now enter up to 20 characters. If fewer than 20 are\n"
22: " entered, make the last one an exclamation mark (!).\n"
23: "5. Enter any amount of whitespace, followed by an integer.\n"
24: "6. Finally, enter at least three more characters, "
25: "then press Enter.\n\n"
26: "Start entering data on the following line:\n";
28: int i1, i2, i3;
29: char c1, c2, c3;
31: cin >> i1; cin.ignore(80, '\n');
32: cin >> i2; cin.ignore(20, '!');
33: cin >> i3;
34: cin >> c1;
35: cin.get(c2); //This statement will read a whitespace character.
36: cin.get(c3); //And so will this one.
38: cout << "\nHere are the 3 integers and 3 characters read in:\n"
39: << "i1: " << i1 << "\ni2: " << i2 << "\ni3: " << i3 << "\n"
40: << "c1: " << c1 << "<<\n"
41: << "c2: " << c2 << "<<\n"
42: << "c3: " << c3 << "<<\n";
43: cout << endl;
44: }